atof() in C – Syntax, Use and Example

Write a C program to input string representation of number and convert string to double using atof() library function. How to convert string to double using atof() library function in C programming?

atof() library function

atof() function converts string to floating point number. The library function is defined in stdlib.h header file.

Syntax of atof() function

double atof (const char* str);
  • It accepts pointer constant to character str which is string representation of floating pointer number.
  • On success, it returns converted floating point number as double type. If the given string str has no possible conversion then returns 0.0.

Important note:

Example program to use atof() function

/**
 * C program to convert string to double using atof() library function.
 */

#include <stdio.h>
#include <stdlib.h>     // Used for atof()


int main()
{
    char number[30];
    double decimalNumber;


    /* Input string representation of floating pointer number from user. */
    printf("Enter any number: ");
    fgets(number, 30, stdin);


    /* Convert string representation of number to double */
    decimalNumber = atof(number);


    /* Use %f, %lf, %llf to print floating point number */
    printf("Converted floating point number = %lf\n", decimalNumber);


    return 0;
}

Output

Enter any number: 1.5
Converted floating point number = 1.500000

Enter any number: 1
Converted floating point number = 1.000000

Enter any number: 01
Converted floating point number = 1.000000

Enter any number: 2.5
Converted floating point number = 2.500000

Enter any number: a2
Converted floating point number = 0.000000

Enter any number: 22.2a
Converted floating point number = 22.200000

Enter any number: 2.2.2.2
Converted floating point number = 2.200000

Enter any number: 9999999999999999999999999999999999999999999999999999
Converted floating point number = 99999999999999991000000000000.000000

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>