The C strtod() function converts checked text to double. It skips leading white space, parses the longest valid floating-point prefix, and exposes where parsing stopped through endptr. This makes validation possible.
This function is declared in <stdlib.h>. Its contract matters as much as its call: validate every required precondition, check any documented sentinel, and keep ownership or host effects clear in the surrounding code. Success produces a value, moves endptr past at least one converted character, and leaves errno free of ERANGE. No digits means endptr equals str. Range failure sets errno to ERANGE and returns HUGE_VAL; trailing input is visible at *endptr. The examples below move from the direct call to an edge condition and a practical use.
Syntax
Start with this concrete strtod() call:
C
strtod("12.5kg", &end)
Call
What it does
strtod("12.5kg", &end)
Converts checked text to double using the concrete values shown.
Include <stdlib.h>. Also include headers that declare any types, limits, locale tools, or I/O functions used around the call.
Step 3. No valid numeric prefix advances the endpoint.
Step 4. Equality with the starting pointer detects the failure.
Example 3 — Check a range error
This complete program demonstrates a distinct part of the strtod() contract and checks the result or precondition that matters for the scenario.
C
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *text="1e99999"; char *end;
errno=0;
double value=strtod(text, &end);
if (errno==ERANGE) puts("out of range");
else printf("%.2f\n", value);
return 0;
}
Output
out of range
How It Works
Step 1. Reset errno immediately before conversion.
Step 2. Parse a value beyond the destination range.
Step 3. Check ERANGE after ensuring conversion was attempted.
Step 4. Reject the saturated or infinite result instead of using it.
Frequently Asked Questions
strtod() converts checked text to double. It skips leading white space, parses the longest valid floating-point prefix, and exposes where parsing stopped through endptr. This makes validation possible.
Include <stdlib.h> before calling strtod().
Success produces a value, moves endptr past at least one converted character, and leaves errno free of ERANGE. No digits means endptr equals str. Range failure sets errno to ERANGE and returns HUGE_VAL; trailing input is visible at *endptr.
Set errno to 0 before the call, inspect endptr to require digits and reject trailing text, then check ERANGE.
The function is specified by the C standard library. Exact limits, locale behavior, environment behavior, allocation capacity, or host effects can still vary where relevant.