Convert a string to a double in C

This example program demonstrates how to convert a string to a double (floating point value) in C using atof and strtof.

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

static void
run_strtod (const char * input)
{
    double output;
    char * end;

    printf ("With strtod, '%s'", input);

    output = strtod (input, & end);

    if (end == input) {
        printf (" is not a valid number.\n");
    }
    else {
        printf (" becomes %g\n", output);
    }
}

static void
run_atof (const char * input)
{
    printf ("With atof, '%s' becomes %g.\n", input, atof (input));
}

int main ()
{
    const char * number = "42.5";

    /* Both strtod and atof can cope with whitespace before the
       number. */

    const char * whitespace_number = "    747.149e9";
    const char * zero = "0";
    const char * not_a_number = "cat";

    /* The function atof can convert strings into doubles, but it
       doesn't distinguish between "zero" and failure. */

    run_atof (number);
    run_atof (whitespace_number);
    run_atof (zero);
    run_atof (not_a_number);

    /* Use a function to run on each of these. */

    run_strtod (number);
    run_strtod (whitespace_number);
    run_strtod (zero);
    run_strtod (not_a_number);

    return 0;
}

(download)

It outputs the following:

With atof, '42.5' becomes 42.5.
With atof, '    747.149e9' becomes 7.47149e+11.
With atof, '0' becomes 0.
With atof, 'cat' becomes 0.
With strtod, '42.5' becomes 42.5
With strtod, '    747.149e9' becomes 7.47149e+11
With strtod, '0' becomes 0
With strtod, 'cat' is not a valid number.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer