C programming atof stdlib.h

In C programming the <stdlib.h> atof function converts the const char* passed as argument to double type.The declaration of the function is shown below.

double atof( const char* x);

x – A const char* type.If the argument passed is a ‘string’ type or ‘string’ variable it is an error.

Return type
double – The string converted to double value is returned.

Some points to note:

i) If the argument passed is a combination of number and non-number characters with the number occurring at the initial part,then only the number is converted to the double type.The non-number char part is neglected.

ii) If the argument passed is only non-number characters then 0 is returned.

iii) It is not possible to obtain the number ‘NaN‘(Not a Number) and ‘±∞‘(infinity) using this function.For this you can use some other function like strtod.

Code example

char c1[] = “22.90” , c2[] = “90.56Text” , c3[] = “Text” ;

printf(“%lf”, atof( c1 ) ) ;
printf(“\n%lf”, atof( c2 ) ) ;
printf(“\n%lf”, atof( c3 ) ) ;

Output in Visual Studio,


In the third output the argument passed is a string,since as string cannot be converted to double type 0 is returned.

*Side Note

Except for the behavior on error ‘atof’ is equivalent to ,

strtod( nptr , (char **)NULL )