Guido van Rossum | 2b7e04a | 1995-02-19 15:54:36 +0000 | [diff] [blame] | 1 | |
| 2 | /* Just in case you haven't got an atof() around... |
| 3 | This one doesn't check for bad syntax or overflow, |
| 4 | and is slow and inaccurate. |
| 5 | But it's good enough for the occasional string literal... */ |
| 6 | |
Martin v. Löwis | 4f1cd8b | 2001-07-26 13:41:06 +0000 | [diff] [blame] | 7 | #include "pyconfig.h" |
Guido van Rossum | 2b7e04a | 1995-02-19 15:54:36 +0000 | [diff] [blame] | 8 | |
| 9 | #include <ctype.h> |
| 10 | |
Thomas Wouters | f70ef4f | 2000-07-22 18:47:25 +0000 | [diff] [blame] | 11 | double atof(char *s) |
Guido van Rossum | 2b7e04a | 1995-02-19 15:54:36 +0000 | [diff] [blame] | 12 | { |
| 13 | double a = 0.0; |
| 14 | int e = 0; |
| 15 | int c; |
| 16 | while ((c = *s++) != '\0' && isdigit(c)) { |
| 17 | a = a*10.0 + (c - '0'); |
| 18 | } |
| 19 | if (c == '.') { |
| 20 | while ((c = *s++) != '\0' && isdigit(c)) { |
| 21 | a = a*10.0 + (c - '0'); |
| 22 | e = e-1; |
| 23 | } |
| 24 | } |
| 25 | if (c == 'e' || c == 'E') { |
| 26 | int sign = 1; |
| 27 | int i = 0; |
| 28 | c = *s++; |
| 29 | if (c == '+') |
| 30 | c = *s++; |
| 31 | else if (c == '-') { |
| 32 | c = *s++; |
| 33 | sign = -1; |
| 34 | } |
| 35 | while (isdigit(c)) { |
| 36 | i = i*10 + (c - '0'); |
| 37 | c = *s++; |
| 38 | } |
| 39 | e += i*sign; |
| 40 | } |
| 41 | while (e > 0) { |
| 42 | a *= 10.0; |
| 43 | e--; |
| 44 | } |
| 45 | while (e < 0) { |
| 46 | a *= 0.1; |
| 47 | e++; |
| 48 | } |
| 49 | return a; |
| 50 | } |