atof - Linux


atof (ascii to float) converts a string of decimal ASCII digits into a double value. It is primarily used to parse text-based numeric input or read data from files where numeric values are stored as ASCII strings.


double atof(const char *str);
  • str: A null-terminated string containing a decimal ASCII number.




Basic Usage:

# Convert the string "123.45" to a double
double number = atof("123.45");

Parsing a String with Embedded Whitespace:

# Convert the string "  123.45  " to a double, ignoring whitespace
double number = atof("  123.45  ");

Handling Invalid Input:

# Convert the string "abc" to a double, resulting in NaN (Not a Number)
double number = atof("abc");

Common Issues

  • Invalid Input: If the string contains non-numeric characters, atof returns NaN.
  • Overflow/Underflow: Converting very large or small numbers can result in overflow or underflow, leading to inaccurate results.


atof can be integrated with other commands to process numeric data:

# Read numeric values from a file and sum them
double sum = 0;
FILE *file = fopen("numbers.txt", "r");
char buffer[100];
while (fgets(buffer, 100, file)) {
    double number = atof(buffer);
    sum += number;

Related Commands

  • strtod: Converts a string to a double with more advanced control over the conversion process.
  • atoi: Converts an ASCII string to an integer.
  • atol: Converts an ASCII string to a long integer.