Quick links
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?
Also see how to convert string to integer using atoi() function?
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 stringstr
has no possible conversion then returns0.0
.
Important note:
atof()
behaviour is undefined if given stringstr
overflows or underflows double precision floating pointer number range.- The function ignores any leading and trailing whitespaces.
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 😉