Format
#include <stdlib.h> double strtod(const char *nptr, char **endptr);
Language Level: ANSI
Threadsafe: Yes.
Description
The strtod() function converts a character string to a double-precision value. The parameter nptr points to a sequence of characters that can be interpreted as a numeric value of the type double. This function stops reading the string at the first character that it cannot recognize as part of a number. This character can be the null character at the end of the string.
The strtod() function expects nptr to point to a string with the following form:
>>-+------------+--+-----+--+-digits--+---+--+--------+-+-------> '-whitespace-' +-&rbl;+&rbl;-+ | '-.-' '-digits-' | '-&rbl;-&rbl;-' '-.--digits-----------------' >--+------------------------+---------------------------------->< '-+-e-+--+-----+--digits-' '-E-' +-&rbl;+&rbl;-+ '-&rbl;-&rbl;-'
The first character that does not fit this form stops the scan.
The behavior of this function is affected by the LC_NUMERIC category of the current locale.
Return Value
The strtod() function returns the value of the floating-point number, except when the representation causes an underflow or overflow. For an overflow, it returns -HUGE_VAL or +HUGE_VAL; for an underflow, it returns 0.
In both cases, errno is set to ERANGE, depending on the base of the value. If the string pointed to by nptr does not have the expected form, no conversion is performed and the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a NULL pointer.
The strtod() function does not fail if a character other than a digit follows an E or e read in as an exponent. For example, 100elf will be converted to the floating-point value 100.0.
Example that uses strtod()
This example converts the strings to a double value. It prints out the converted value and the substring that stopped the conversion.
#include <stdlib.h> #include <stdio.h> int main(void) { char *string, *stopstring; double x; string = "3.1415926This stopped it"; x = strtod(string, &stopstring); printf("string = %s\n", string); printf(" strtod = %lf\n", x); printf(" Stopped scan at %s\n\n", stopstring); string = "100ergs"; x = strtod(string, &stopstring); printf("string = \"%s\"\n", string); printf(" strtod = %lf\n", x); printf(" Stopped scan at \"%s\"\n\n", stopstring); } /***************** Output should be similar to: ***************** string = 3.1415926This stopped it strtod = 3.141593 Stopped scan at This stopped it string = 100ergs strtod = 100.000000 Stopped scan at ergs */
Related Information
(C) Copyright IBM Corporation 1992, 2006. All Rights Reserved.