From 8484ea3fb2333486535f2a0108246fc75f89c0c7 Mon Sep 17 00:00:00 2001 From: Petri Lehtinen Date: Tue, 1 Nov 2011 20:49:15 +0200 Subject: [PATCH] Remove '+' and leading zeros from exponents in the encoder Fixes GH-39. --- src/strconv.c | 23 ++++++++++++++++++++++- test/suites/valid/real-capital-e/output | 2 +- test/suites/valid/real-exponent/output | 2 +- test/suites/valid/real-fraction-exponent/output | 2 +- 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/strconv.c b/src/strconv.c index 801fad2..caa9ab8 100644 --- a/src/strconv.c +++ b/src/strconv.c @@ -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; } diff --git a/test/suites/valid/real-capital-e/output b/test/suites/valid/real-capital-e/output index 88e90ce..9a739f2 100644 --- a/test/suites/valid/real-capital-e/output +++ b/test/suites/valid/real-capital-e/output @@ -1 +1 @@ -[1e+22] \ No newline at end of file +[1e22] \ No newline at end of file diff --git a/test/suites/valid/real-exponent/output b/test/suites/valid/real-exponent/output index ac910d6..5ffc719 100644 --- a/test/suites/valid/real-exponent/output +++ b/test/suites/valid/real-exponent/output @@ -1 +1 @@ -[1.2299999999999999e+47] \ No newline at end of file +[1.2299999999999999e47] \ No newline at end of file diff --git a/test/suites/valid/real-fraction-exponent/output b/test/suites/valid/real-fraction-exponent/output index 4b87bda..66a3c81 100644 --- a/test/suites/valid/real-fraction-exponent/output +++ b/test/suites/valid/real-fraction-exponent/output @@ -1 +1 @@ -[1.23456e+80] \ No newline at end of file +[1.23456e80] \ No newline at end of file -- 2.7.4