Remove '+' and leading zeros from exponents in the encoder
authorPetri Lehtinen <petri@digip.org>
Tue, 1 Nov 2011 18:49:15 +0000 (20:49 +0200)
committerPetri Lehtinen <petri@digip.org>
Tue, 1 Nov 2011 18:50:16 +0000 (20:50 +0200)
Fixes GH-39.

src/strconv.c
test/suites/valid/real-capital-e/output
test/suites/valid/real-exponent/output
test/suites/valid/real-fraction-exponent/output

index 801fad2..caa9ab8 100644 (file)
@@ -76,6 +76,7 @@ int jsonp_strtod(strbuffer_t *strbuffer, double *out)
 int jsonp_dtostr(char *buffer, size_t size, double value)
 {
     int ret;
+    char *start, *end;
     size_t length;
 
     ret = snprintf(buffer, size, "%.17g", value);
@@ -95,14 +96,34 @@ int jsonp_dtostr(char *buffer, size_t size, double value)
     if(strchr(buffer, '.') == NULL &&
        strchr(buffer, 'e') == NULL)
     {
-        if(length + 2 >= size) {
+        if(length + 3 >= size) {
             /* No space to append ".0" */
             return -1;
         }
         buffer[length] = '.';
         buffer[length + 1] = '0';
+        buffer[length + 2] = '\0';
         length += 2;
     }
 
+    /* Remove leading '+' from positive exponent. Also remove leading
+       zeros from exponents (added by some printf() implementations) */
+    start = strchr(buffer, 'e');
+    if(start) {
+        start++;
+        end = start + 1;
+
+        if(*start == '-')
+            start++;
+
+        while(*end == '0')
+            end++;
+
+        if(end != start) {
+            memmove(start, end, length - (size_t)(end - buffer));
+            length -= (size_t)(end - start);
+        }
+    }
+
     return (int)length;
 }
index 88e90ce..9a739f2 100644 (file)
@@ -1 +1 @@
-[1e+22]
\ No newline at end of file
+[1e22]
\ No newline at end of file
index ac910d6..5ffc719 100644 (file)
@@ -1 +1 @@
-[1.2299999999999999e+47]
\ No newline at end of file
+[1.2299999999999999e47]
\ No newline at end of file
index 4b87bda..66a3c81 100644 (file)
@@ -1 +1 @@
-[1.23456e+80]
\ No newline at end of file
+[1.23456e80]
\ No newline at end of file