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
60 while (isspace(*p
)) p
++;
62 // Handle optional sign
66 case '-': negative
= 1; // Fall through to increment position
75 // Process string of digits
78 number
= number
* 10. + (*p
- '0');
83 // Process decimal part
90 number
= number
* 10. + (*p
- '0');
96 exponent
-= num_decimals
;
106 if (negative
) number
= -number
;
108 // Process an exponent string
109 if (*p
== 'e' || *p
== 'E')
111 // Handle optional sign
115 case '-': negative
= 1; // Fall through to increment pos
119 // Process string of digits
123 n
= n
* 10 + (*p
- '0');
133 if (exponent
< __DBL_MIN_EXP__
||
134 exponent
> __DBL_MAX_EXP__
)
157 if (!is_real(number
)) errno
= ERANGE
;
158 if (endptr
) *endptr
= p
;