1 /* Copyright (C) 1991, 1992, 1997, 1999, 2003, 2006 Free Software Foundation, Inc.
3 This program is free software: you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 3 of the License, or
6 (at your option) any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>. */
28 /* Convert NPTR to a double. If ENDPTR is not NULL, a pointer to the
29 character after the last one used in the number is put in *ENDPTR. */
31 strtod (const char *nptr, char **endptr)
33 register const char *s;
36 /* The number so far. */
39 int got_dot; /* Found a decimal point. */
40 int got_digit; /* Seen any digits. */
42 /* The exponent of the number. */
54 while (isspace ((unsigned char) *s))
58 sign = *s == '-' ? -1 : 1;
59 if (*s == '-' || *s == '+')
68 if ('0' <= *s && *s <= '9')
72 /* Make sure that multiplication by 10 will not overflow. */
73 if (num > DBL_MAX * 0.1)
74 /* The value of the digit doesn't matter, since we have already
75 gotten as many digits as can be represented in a `double'.
76 This doesn't necessarily mean the result will overflow.
77 The exponent may reduce it to within range.
79 We just need to record that there was another
80 digit so that we can multiply by 10 later. */
83 num = (num * 10.0) + (*s - '0');
85 /* Keep track of the number of digits after the decimal point.
86 If we just divided by 10 here, we would lose precision. */
90 else if (!got_dot && *s == '.')
91 /* Record that we have found the decimal point. */
94 /* Any other character terminates the number. */
101 if (tolower ((unsigned char) *s) == 'e')
103 /* Get the exponent specified after the `e' or `E'. */
110 exp = strtol (s, &end, 10);
113 /* The exponent overflowed a `long int'. It is probably a safe
114 assumption that an exponent that cannot be represented by
115 a `long int' exceeds the limits of a `double'. */
124 /* There was no exponent. Reset END to point to
125 the 'e' or 'E', so *ENDPTR will be set there. */
126 end = (char *) s - 1;
133 *endptr = (char *) s;
138 /* Multiply NUM by 10 to the EXPONENT power,
139 checking for overflow and underflow. */
143 if (num < DBL_MIN * pow (10.0, (double) -exponent))
146 else if (exponent > 0)
148 if (num > DBL_MAX * pow (10.0, (double) -exponent))
152 num *= pow (10.0, (double) exponent);
157 /* Return an overflow error. */
159 return HUGE_VAL * sign;
162 /* Return an underflow error. */
164 *endptr = (char *) nptr;
169 /* There was no number. */
171 *endptr = (char *) nptr;