Saturday, February 13, 2016

Converting a string with decimal numbers in C

Here's an example of how to convert a string with decimal numbers into a variable in the C programming language.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

int
main(int argc, char **argv)
{
    char    *str = "12.34";
    char    *end;
    double  val;

    errno = 0;
    val = (double)strtod(str, &end);
    if (val == 0 && *end != '\0') {
        return (EINVAL);
    }

    if (errno == ERANGE) {
        return (ERANGE);
    }

    printf("Converted string %s to double %f\n", str, val);

    return (0);
}
And running this little program we get:
$ ./example
Converted string 12.34 to double 12.340000

No comments:

Post a Comment