strtod
Convert ASCII string to floating point
Interface
#include <stdlib.h>
double | strtod (const char * restrict nptr, char ** restrict endptr) |
float | strtof (const char * restrict nptr, char ** restrict endptr) |
long double | strtold (const char * restrict nptr, char ** restrict endptr) |
Description
These conversion functions convert the initial portion of the string pointed to bynptr
to double, float, and long double representation, respectively.
The expected form of the string is an optional plus ("+") or minus sign ("-") followed by either:
- a decimal significand consisting of a sequence of decimal digits optionally containing a decimal-point character, or
- a hexadecimal significand consisting of a "0X" or "0x" followed by a sequence of hexadecimal digits optionally containing a decimal-point character.
Example 1
#include <stdio.h> #include <stdlib.h> int main () { char number[10] = "3.141592", *end; double pi = strtod(number, &end); printf("pi = %lf\n", pi); return 0; }
Output:pi = 3.141592
Return Values
The strtod, strtof and strtold functions return the converted value, if any. Ifendptr
is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr
.
If no conversion is performed, zero is returned and the value of nptr
is stored in the location referenced by endptr
.
If the correct value would cause overflow, plus or minus HUGE_VAL, HUGE_VALF, or HUGE_VALL is returned (according to the sign and type of the return value), and ERANGE is stored in errno
. If the correct value would cause underflow, zero is returned and ERANGE is stored in errno
.