w3resource

C atof() function

C atof() function - Convert character string to float

The atof() function is used to convert a character string to a double-precision floating-point value.

Syntax:

double atof(const char *str)

Parameters:

Name Description Required /Optional
str String to be converted. Required

Return value from atof()

  • Returns a double value that is produced by interpreting the input characters as a number.
  • If the function cannot convert the input to a value of that type return value is 0.

Example: atof() function

The following example shows the usage of atof() function.


#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
    double x;
    char *s;
 
    s = "-3423.12E-15";
    printf("String value: %s",s);
    x = atof(s);   
    printf("\nDouble-precision floating-point value = %.4e\n",x);
    s = "+3423.12E-15";
    printf("\nString value: %s",s);
    x = atof(s);   
    printf("\nDouble-precision floating-point value = %.4e\n",x);
    s = "3423.12E-15";
    printf("\nString value: %s",s);
    x = atof(s);   
    printf("\nDouble-precision floating-point value = %.4e\n",x);
    s = "4567.456";
    printf("\nString value: %s",s);
    x = atof(s);   
    printf("\nDouble-precision floating-point value = %.4e\n",x);
    s = "4567";
    printf("\nString value: %s",s);
    x = atof(s);   
    printf("\nDouble-precision floating-point value = %.4e\n",x);
}

Output:

String value: -3423.12E-15
Double-precision floating-point value = -3.4231e-012

String value: +3423.12E-15
Double-precision floating-point value = 3.4231e-012

String value: 3423.12E-15
Double-precision floating-point value = 3.4231e-012

String value: 4567.456
Double-precision floating-point value = 4.5675e+003

String value: 4567
Double-precision floating-point value = 4.5670e+003

C Programming Code Editor:

Previous C Programming: C stdlib.h Home
Next C Programming: C atoi()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q