From 2327b87304055e29e466d5653420bf35578cbedd Mon Sep 17 00:00:00 2001 From: Adam Sutton Date: Sun, 23 Jun 2013 13:34:01 +0100 Subject: [PATCH] misc: fix and simplify string procesing bug previously this could create wildly inaccurate results for numbers with a larger number of fractional digits. Combined with inaccuracy of representing some numbers this could result in a roundtrip str -> double -> str ending up with complete garbage. --- src/misc/dbl.c | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/misc/dbl.c b/src/misc/dbl.c index 05e5a6dd..a3fed6e3 100644 --- a/src/misc/dbl.c +++ b/src/misc/dbl.c @@ -31,31 +31,32 @@ double my_str2double(const char *str, const char **endp) { - double ret = 1.0f; - int n = 0, m = 0, o = 0, e = 0; + double ret = 0.0, t = 0.1; + int n = 0, e = 0; + /* Negative */ if(*str == '-') { - ret = -1.0f; + n = 1; str++; } + /* Integer */ while(*str >= '0' && *str <= '9') - n = n * 10 + *str++ - '0'; - - if(*str != '.') { - ret *= n; - } else { + ret = ret * 10 + *str++ - '0'; + /* Fracton */ + if(*str == '.') { str++; - while(*str >= '0' && *str <= '9') { - o = o * 10 + *str++ - '0'; - m--; + ret += (*str++ - '0') * t; + t /= 10; } - - ret *= (n + pow(10, m) * o); } + /* Negate */ + if (n) ret *= -1; + + /* Exponential */ if(*str == 'e' || *str == 'E') { int esign = 1; str++;