4 * Convert string to double
6 * Copyright (C) 2002 Michael Ringgaard. All rights reserved.
7 * Copyright 2006-2008 H. Peter Anvin - All Rights Reserved
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the project nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
33 * OF THE POSSIBILITY OF SUCH DAMAGE.
41 static inline int is_real(double x
)
43 const double Inf
= 1.0 / 0.0;
44 return (x
< Inf
) && (x
>= -Inf
);
47 double strtod(const char *str
, char **endptr
)
52 char *p
= (char *)str
;
57 const double Inf
= 1.0 / 0.0;
59 // Skip leading whitespace
63 // Handle optional sign
67 negative
= 1; // Fall through to increment position
77 // Process string of digits
79 number
= number
* 10. + (*p
- '0');
84 // Process decimal part
89 number
= number
* 10. + (*p
- '0');
95 exponent
-= num_decimals
;
98 if (num_digits
== 0) {
106 // Process an exponent string
107 if (*p
== 'e' || *p
== 'E') {
108 // Handle optional sign
112 negative
= 1; // Fall through to increment pos
117 // Process string of digits
119 while (isdigit(*p
)) {
120 n
= n
* 10 + (*p
- '0');
130 if (exponent
< __DBL_MIN_EXP__
|| exponent
> __DBL_MAX_EXP__
) {
150 if (!is_real(number
))