C Language: strtod function
(Convert String to Double)
In the C Programming Language, the strtod function converts a string to a double.
The strtod function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.
Syntax
The syntax for the strtod function in the C Language is:
double strtod(const char *nptr, char **endptr);
Parameters or Arguments
- nptr
- A pointer to a string to convert to a double.
- endptr
- It is used by the strtod function to indicate where the conversion stopped. The strtod function will modify endptr (if endptr is not a null pointer) so that endptr points to the first character that was not converted.
Returns
The strtod function returns the double representation of a string. The strtod function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.
If the strtod function converts a value that is too large or too small to convert, it will store ERANGE in errono.
Required Header
In the C Language, the required header for the strtod function is:
#include <stdlib.h>
Applies To
In the C Language, the strtod function can be used in the following versions:
- ANSI/ISO 9899-1990
strtod Example
Let's look at an example to see how you would use the strtod function in a C program:
/* Example using strtod by TechOnTheNet.com */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ char value[10]; char *eptr; double result; /* Copy a value into the variable */ /* It's okay to have whitespace before the number */ strcpy(value, " 958"); /* Convert the provided value to a double */ result = strtod(value, &eptr); /* If the result is 0, test for an error */ if (result == 0) { /* If the value provided was out of range, display a warning message */ if (errno == ERANGE) printf("The value provided was out of range\n"); } /* Display the converted result */ printf("%f decimal\n", result); /* Copy a hexadecimal value into the variable */ strcpy(value, "0x8b2"); /* Convert the hexadecimal provided value to a double */ result = strtod(value, &eptr); /* If the result is 0, test for an error */ if (result == 0) { /* If the value provided was out of range, display a warning message */ if (errno == ERANGE) printf("The value provided was out of range\n"); } /* Display the converted result */ printf("%f decimal\n", result); return 0; }
When compiled and run, this application will output:
958.000000 decimal 2226.000000 decimal
Similar Functions
Other C functions that are similar to the strtod function:
See Also
Other C functions that are noteworthy when dealing with the strtod function:
Advertisements