4 // Convert string to double
6 // Copyright (C) 2002 Michael Ringgaard. All rights reserved.
7 // Copyright (C) 2006 H. Peter Anvin.
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 "AS IS" AND
23 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
26 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 static inline int is_real(double x
)
41 const double Inf
= 1.0/0.0;
42 return (x
< Inf
) && (x
>= -Inf
);
45 double strtod(const char *str
, char **endptr
)
50 char *p
= (char *) str
;
55 const double Inf
= 1.0/0.0;
57 // Skip leading whitespace
58 while (isspace(*p
)) p
++;
60 // Handle optional sign
64 case '-': negative
= 1; // Fall through to increment position
73 // Process string of digits
76 number
= number
* 10. + (*p
- '0');
81 // Process decimal part
88 number
= number
* 10. + (*p
- '0');
94 exponent
-= num_decimals
;
104 if (negative
) number
= -number
;
106 // Process an exponent string
107 if (*p
== 'e' || *p
== 'E')
109 // Handle optional sign
113 case '-': negative
= 1; // Fall through to increment pos
117 // Process string of digits
121 n
= n
* 10 + (*p
- '0');
131 if (exponent
< __DBL_MIN_EXP__
||
132 exponent
> __DBL_MAX_EXP__
)
155 if (!is_real(number
)) errno
= ERANGE
;
156 if (endptr
) *endptr
= p
;