webmcp

changeset 429:387a303918a6

Handle special corner case for integral floats in json.export(...)
author jbe
date Thu Jan 14 18:01:33 2016 +0100 (2016-01-14)
parents 52ebde158c92
children 33d43f5a319b
files libraries/json/json.c
line diff
     1.1 --- a/libraries/json/json.c	Thu Jan 14 17:40:49 2016 +0100
     1.2 +++ b/libraries/json/json.c	Thu Jan 14 18:01:33 2016 +0100
     1.3 @@ -1119,10 +1119,16 @@
     1.4        if (isnan(num)) return luaL_error(L, "JSON export not possible for NaN value");
     1.5        // throw error if number is positive or negative infinity:
     1.6        if (isinf(num)) return luaL_error(L, "JSON export not possible for infinite numbers");
     1.7 -      // determine necessary precision to represent double precision floating point number:
     1.8 -      sprintf(numstr, "%.15g", num);  // NOTE: e.g. 0.009 should not be 0.008999999999999999
     1.9 -      if (strtod(numstr, NULL) != num) sprintf(numstr, "%.16g", num);
    1.10 -      if (strtod(numstr, NULL) != num) sprintf(numstr, "%.17g", num);
    1.11 +      // check if float is integral:
    1.12 +      if (trunc(num) == num) {
    1.13 +        // if yes, use maximum precision:
    1.14 +        sprintf(numstr, "%.17g", num);  // NOTE: e.g. 12345678901234560
    1.15 +      } else {
    1.16 +        // determine necessary precision to represent double precision floating point number:
    1.17 +        sprintf(numstr, "%.15g", num);  // NOTE: e.g. 0.009 should not be 0.008999999999999999
    1.18 +        if (strtod(numstr, NULL) != num) sprintf(numstr, "%.16g", num);
    1.19 +        if (strtod(numstr, NULL) != num) sprintf(numstr, "%.17g", num);
    1.20 +      }
    1.21        // add string encoding of the number to the output buffer:
    1.22        luaL_addstring(&buf, numstr);
    1.23  #if LUA_VERSION_NUM >= 503

Impressum / About Us