Browse Source

Improved JSON float number export

Marco Bambini 5 years ago
parent
commit
350e620400

+ 2 - 1
src/optionals/gravity_opt_json.c

@@ -55,7 +55,8 @@ static bool JSON_stringify (gravity_vm *vm, gravity_value_t *args, uint16_t narg
     const char *v = NULL;
     
     if (VALUE_ISA_NULL(value) || (VALUE_ISA_UNDEFINED(value))) v = "null";
-    else if (VALUE_ISA_FLOAT(value)) {snprintf(vbuffer, sizeof(vbuffer), "%g", value.f); v = vbuffer;}
+    // was %g but we don't like scientific notation nor the missing .0 in case of float number with no decimals
+    else if (VALUE_ISA_FLOAT(value)) {snprintf(vbuffer, sizeof(vbuffer), "%f", value.f); v = vbuffer;}
     else if (VALUE_ISA_BOOL(value)) v = (value.n) ? "true" : "false";
     else if (VALUE_ISA_INT(value)) {
         #if GRAVITY_ENABLE_INT64

+ 1 - 1
src/optionals/gravity_opt_math.c

@@ -648,7 +648,7 @@ static bool math_round (gravity_vm *vm, gravity_value_t *args, uint16_t nargs, u
             
             // convert f to string
             char buffer[512];
-            snprintf(buffer, sizeof(buffer), "%g", f);
+            snprintf(buffer, sizeof(buffer), "%f", f);
             
             // trunc c string to the requested ndigits
             char *p = buffer;

+ 2 - 1
src/shared/gravity_hash.c

@@ -332,7 +332,8 @@ uint32_t gravity_hash_compute_int (gravity_int_t n) {
 
 uint32_t gravity_hash_compute_float (gravity_float_t f) {
     char buffer[24];
-    snprintf(buffer, sizeof(buffer), "%g", f);
+    // was %g but we don't like scientific notation nor the missing .0 in case of float number with no decimals
+    snprintf(buffer, sizeof(buffer), "%f", f);
     return murmur3_32(buffer, (uint32_t)strlen(buffer), HASH_SEED_VALUE);
 }
 

+ 2 - 1
src/utils/gravity_json.c

@@ -291,7 +291,8 @@ void json_add_double (json_t *json, const char *key, double value) {
     json_check_comma(json);
     
     char buffer[512];
-    size_t len = snprintf(buffer, sizeof(buffer), "%g", value);
+    // was %g but we don't like scientific notation nor the missing .0 in case of float number with no decimals
+    size_t len = snprintf(buffer, sizeof(buffer), "%f", value);
 
     if (key) {
         json_write_raw (json, key, strlen(key), true, true);