atof() in C - Source Code Example

In this source code example, we will see how to use the atof() function in C programming with an example.

atof() Function Overview

The atof() function in C is used to convert a string into a floating-point number (double). It's part of the <stdlib.h> library. If the initial portion of the string can't be converted to a double value, it returns 0.0.

Source Code Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Valid floating-point number as a string
    char floatStr1[] = "123.456";
    double float1 = atof(floatStr1);
    printf("%s to double: %f\n", floatStr1, float1);

    // String starts with a valid number but has characters afterward
    char floatStr2[] = "789.101xyz";
    double float2 = atof(floatStr2);
    printf("%s to double: %f\n", floatStr2, float2);

    // String without a valid number at the beginning
    char floatStr3[] = "abc12.34";
    double float3 = atof(floatStr3);
    printf("%s to double: %f\n", floatStr3, float3);

    // Spaces before the number
    char floatStr4[] = "   -56.789";
    double float4 = atof(floatStr4);
    printf("'%s' to double: %f\n", floatStr4, float4);

    return 0;
}

Output

123.456 to double: 123.456000
789.101xyz to double: 789.101000
abc12.34 to double: 0.000000
'   -56.789' to double: -56.789000

Explanation

1. floatStr1 holds a clear floating-point number. atof() converts it to its double representation.

2. For floatStr2, the function starts converting until it encounters a non-numeric character.

3. floatStr3 doesn't start with a number, so atof() gives 0.0.

4. floatStr4 begins with spaces; atof() skips these and then converts the following number.

Note: If the string can't be changed into a floating-point number, atof() will return 0.0.


Comments