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_strtof (const char * input)
{
    double output;
    char * end;

    printf ("With strtof, %s", input);


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

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

    /* Both strtof 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. */

    printf ("With atof: %s -> %g %s -> %g %s -> %g %s -> %g\n",
            number, atof (number),
            whitespace_number, atof (whitespace_number),
            zero, atof (zero),
            not_a_number, atof (not_a_number));
            
    /* Use a function to run on each of these. */

    run_strtof (number);
    run_strtof (whitespace_number);
    run_strtof (zero);
    run_strtof (not_a_number);

    return 0;
}

Download it here.

It outputs the following:

With atof: 42.5 -> 42.5     747.149e9 -> 7.47149e+11 0 -> 0 cat -> 0
With strtof, 42.5 -> 42.5
With strtof,     747.149e9 -> 7.47149e+11
With strtof, 0 -> 0
With strtof, cat is not a valid number.

Ask and answer questions on C in the new C forum

Copyright © Ben Bullock 2009-2012. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (ben.bullock@lemoda.net) / Privacy / Disclaimer