C atof()

The atof() function is defined in the stdlib.h header file. It helps to convert a given string argument(str) into a floating-point value ie type double.


double atof(const char *str); #where str should be a string

 

atof() Parameters: 

The atof() function takes a single parameter. In C language typecasting is supported by stdlib.h headerfile.

Parameter Description Required / Optional
str  the string having the representation of a floating-point number Required

atof() Return Value

The return value of atof() function is a floating-point number as a double value.

Input Return Value
successful double value
invalid conversion zero

Examples of atof()

Example 1: Working of atof() function in C?


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   float f;
   char st[20];
   
   strcpy(st, "23333333");
   f = atof(st);
   printf("String is %s, Float value = %f\n", st, f);

   strcpy(st, "Hi how are you");
   f = atof(st);
   printf("String is %s, Float value = %f\n", st, f);

   return(0);
}

Output:


String is 23333333, Float value = 23333333.000000
String is Hi how are you, Float value = 0.000000

Example 2: How atof() works in C?


#include <stdio.h>

int main (){
  char x[10] = "3.14";
    float pi = atof(x);
    printf("pi value is %f\n", pi);
    return 0;
}

Output:


pi value is 3.140000