like atoi but to float

32.3k Views Asked by At

Is there a function similar to atoi which converts a string to float instead of to integer?

11

There are 11 best solutions below

9
On BEST ANSWER

atof()

(or std::atof() talking C++ - thanks jons34yp)

1
On
#include <stdlib.h>
double atof(const char*);

There's also strtod.

0
On

strtof

From the man page

The strtod(), strtof(), and strtold() functions convert the initial portion of the string pointed to by nptr to double, float, and long double representation, respectively.

The expected form of the (initial portion of the) string is optional leading white space as recognized by isspace(3), an optional plus (‘‘+’’) or minus sign (‘‘-’’) and then either (i) a decimal number, or (ii) a hexadecimal number, or (iii) an infinity, or (iv) a NAN (not-a-number).

/man page>

atof converts a string to a double (not a float as it's name would suggest.)

0
On

Use atof from stdlib.h:

double atof ( const char * str );
9
On

Prefer strtof(). atof() does not detect errors.

5
On
boost::lexical_cast<float>(str);

This template function is included in the popular Boost collection of libraries, which you'll want learn about if you're serious about C++.

12
On

Convert a string to any type (that's default-constructible and streamable):

template< typename T >
T convert_from_string(const std::string& str)
{
  std::istringstream iss(str);
  T result;
  if( !(iss >> result) ) throw "Dude, you need error handling!";
  return result;
}
2
On

As an alternative to the the already-mentioned std::strtof() and boost::lexical_cast<float>(), the new C++ standard introduced

float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);

for error-checking string to floating-point conversions. Both GCC and MSVC support them (remember to #include <string>)

0
On

This would also work ( but C kind of code ):

#include <iostream>

using namespace std;

int main()
{
float myFloatNumber = 0;
string inputString = "23.2445";
sscanf(inputString.c_str(), "%f", &myFloatNumber);
cout<< myFloatNumber * 100;

}

See it here: http://codepad.org/qlHe5b2k

0
On

As an alternative to all above, you may use string stream. http://cplusplus.com/reference/iostream/stringstream/

0
On

Try boost::spirit: fast, type-safe and very efficient:

std::string::iterator begin = input.begin();
std::string::iterator end = input.end();
using boost::spirit::float_;

float val;
boost::spirit::qi::parse(begin,end,float_,val);