atof() Convert a string to double
atof() Convert a string to double
atof() parses a floating-point prefix and returns 0.0 if no conversion can be performed. Invalid input looks like zero; out-of-range behavior is undefined.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
double atof(const char *nptr);
⚙️ Parameters
| nptr Required | A null-terminated string whose initial text contains a floating-point representation. |
|---|
Returns: Returns the converted double value, or 0.0 if no conversion can be performed. Behavior is undefined if the result is outside the representable range.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
3.50
-2.25
⚠️ Warning atof() provides no reliable error or overflow detection. Use strtod() for validated floating-point input and strtol() for integers.
💡 Tip The example uses %f and %.2f for double values. Like atoi(), atof() ignores trailing characters after a valid numeric prefix.
🏷️ Related stdlib.h functions
📚 Related Tutorials
❓ FAQ
QWhy is an atof conversion failure difficult to detect?
ABoth invalid input and a valid 0.0 produce 0.0, and the function provides no end pointer to check whether digits were consumed or trailing junk remains.
QWhat is the difference between atof and atoi?
Aatof returns double and accepts fractional and exponent forms; atoi returns int and parses a decimal integer prefix. Both lack comprehensive error detection.
QHow should I choose between atof and strtod?
Aatof is concise when converting a completely trusted floating-point prefix; for user input, configuration files, or protocol data, prefer strtod. Its end pointer lets you check whether any digits were consumed and whether a suffix remains, and errno can report range errors, whereas atof has difficulty distinguishing invalid input from 0.0.