Dave's Brain

Browse - Programming Tips - How do I convert a string into a float?

Date: 2015apr23
Language: C/C++
Level: beginner

Q.  How do I 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 l = strtoul("12345", NULL, 10); // string to unsigned long

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.