C - using atof to convert between a char / string to float

14. March 2012 08:00

 

This is a short example of using the function atof to convert from a string to float. It is also worth pointing out that this function really returns a double instead of a float and should probably be avoided since it does not support any form of error handling. So strtod should be used instead.

 

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


int main(int argc, char **argv) {
        char *str = "123.45";
        double val1 = atof(str);
        float val2 = atof(str);

        printf("%s -> %f\n", str, val1);
        printf("%s -> %f\n", str, val2);

        return 0;
}

E-mail Kick it! DZone it! del.icio.us Permalink