std::string to float or double



I'm trying to convert std::string to float/double. I tried:

std::string num = "0.6";
double temp = (double)atof(num.c_str());

But it always returns zero. Any other ways?

3/14/2014 4:35:38 PM

Accepted Answer

std::string num = "0.6";
double temp = ::atof(num.c_str());

Does it for me, it is a valid C++ syntax to convert a string to a double.

You can do it with the stringstream or boost::lexical_cast but those come with a performance penalty.

Ahaha you have a Qt project ...

QString winOpacity("0.6");
double temp = winOpacity.toDouble();

Extra note:
If the input data is a const char*, QByteArray::toDouble will be faster.

6/18/2009 2:09:28 PM

The Standard Library (C++11) offers the desired functionality with std::stod :

std::string  s  = "0.6"
std::wstring ws = "0.7"
double d  = std::stod(s);
double dw = std::stod(ws);

I guess the Standard Library converts internally too, but this way makes the code cleaner. Generally for most other basic types, see <string>. There are some new features for C strings, too. See <stdlib.h>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow