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.
This commit is contained in:
parent
c2bc0a6a75
commit
2327b87304
1 changed files with 14 additions and 13 deletions
|
@ -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++;
|
||||
|
|
Loading…
Add table
Reference in a new issue