Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string to float or double

Tags:

c++

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?

like image 374
Max Frai Avatar asked Jun 18 '09 13:06

Max Frai


2 Answers

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.

like image 99
TimW Avatar answered Oct 11 '22 15:10

TimW


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>

like image 42
ManuelSchneid3r Avatar answered Oct 11 '22 15:10

ManuelSchneid3r