Date: 2015apr23
Date: 2026sep24
Language: C/C++
Level: novice
Q. C/C++: How to convert a string into a float
A. Like this:
float x = (float) atof("123.45");
Oddly, the atof() -- ascii to float -- returns a double not a float so you have
to cast it.
Other conversions:
double d = atof("123.45"); // String to double
int i = atoi("123"); // String to int
long l = strtol("12345", NULL, 10); // String to long
unsigned long ul = strtoul("12345", NULL, 10); // String to unsigned long
Full Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
{
double d = atof("123.45"); // String to double
printf("123.45 is %lf as a double\n", d);
}
{
int i = atoi("123"); // String to int
printf("123 is %d as int\n", i);
}
{
long l = strtol("12345", NULL, 10); // String to long
printf("12345 is %ld as long\n", l);
}
{
unsigned long ul = strtoul("12345", NULL, 10); // String to unsigned long
printf("12345 is %lu as unsigned long\n", ul);
}
}
Output:
123.45 is 123.450000 as a double
123 is 123 as int
12345 is 12345 as long
12345 is 12345 as unsigned long