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?
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.
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);
Generally for most other basic types, see <string>
. There are some new features for C strings, too. See <stdlib.h>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With