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.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

double atof(const char *nptr);

⚙️ Parameters

nptr RequiredA 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏