std::string to float or double

C++

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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>

Solution 3 - C++

Lexical cast is very nice.

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>

using std::endl;
using std::cout;
using std::string;
using boost::lexical_cast;

int main() {
    string str = "0.6";
    double dub = lexical_cast<double>(str);
    cout << dub << endl;
}

Solution 4 - C++

You can use std::stringstream:

   #include <sstream>
   #include <string>
   template<typename T>
   T StringToNumber(const std::string& numberAsString)
   {
      T valor;

      std::stringstream stream(numberAsString);
      stream >> valor;
      if (stream.fail()) {
         std::runtime_error e(numberAsString);
         throw e;
      }
      return valor;
   }

Usage:

double number= StringToNumber<double>("0.6");

Solution 5 - C++

Yes, with a lexical cast. Use a stringstream and the << operator, or use Boost, they've already implemented it.

Your own version could look like:

template<typename to, typename from>to lexical_cast(from const &x) {
  std::stringstream os;
  to ret;

  os << x;
  os >> ret;

  return ret;  
}

Solution 6 - C++

You can use boost lexical cast:

#include <boost/lexical_cast.hpp>

string v("0.6");
double dd = boost::lexical_cast<double>(v);
cout << dd << endl;

Note: boost::lexical_cast throws exception so you should be prepared to deal with it when you pass invalid value, try passing string("xxx")

Solution 7 - C++

If you don't want to drag in all of boost, go with strtod(3) from <cstdlib> - it already returns a double.

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

using namespace std;

int main()  {
    std::string  num = "0.6";
    double temp = ::strtod(num.c_str(), 0);

    cout << num << " " << temp << endl;
    return 0;
}

Outputs:

$ g++ -o s s.cc
$ ./s
0.6 0.6
$

Why atof() doesn't work ... what platform/compiler are you on?

Solution 8 - C++

I had the same problem in Linux

double s2f(string str)
{
 istringstream buffer(str);
 double temp;
 buffer >> temp;
 return temp;
}

it works.

Solution 9 - C++

   double myAtof ( string &num){
      double tmp;
      sscanf ( num.c_str(), "%lf" , &tmp);
      return tmp;
   }

Solution 10 - C++

The C++ 11 way is to use std::stod and std::to_string. Both work in Visual Studio 11.

Solution 11 - C++

With C++17, you can use std::from_chars, which is a lighter weight faster alternative to std::stof and std::stod. It doesn't involve any memory allocation or look at the locale, and it is non-throwing.

The std::from_chars function returns a value of type from_chars_result, which is basically a struct with two fields:

struct from_chars_result {
    const char* ptr;
    std::errc ec;
};

By inspecting ec we can tell if the conversion was successful:

#include <iostream>
#include <charconv>

int main()
{
    const std::string str { "12345678901234.123456" };
    double value = 0.0;
    auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
    if (ec != std::errc()) {
        std::cout << "Couldn't convert value";
    }
    
    return 0;
}

NB: you need a fairly up-to-date compiler (e.g. gcc11) for std::from_chars to work with floating point types.

Solution 12 - C++

This answer is backing up litb in your comments. I have profound suspicions you are just not displaying the result properly.

I had the exact same thing happen to me once. I spent a whole day trying to figure out why I was getting a bad value into a 64-bit int, only to discover that printf was ignoring the second byte. You can't just pass a 64-bit value into printf like its an int.

Solution 13 - C++

As to why atof() isn't working in the original question: the fact that it's cast to double makes me suspicious. The code shouldn't compile without #include <stdlib.h>, but if the cast was added to solve a compile warning, then atof() is not correctly declared. If the compiler assumes atof() returns an int, casting it will solve the conversion warning, but it will not cause the return value to be recognized as a double.

#include <stdlib.h>
#include <string>

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

should work without warnings.

Solution 14 - C++

Rather than dragging Boost into the equation, you could keep your string (temporarily) as a char[] and use sprintf().

But of course if you're using Boost anyway, it's really not too much of an issue.

Solution 15 - C++

You don't want Boost lexical_cast for string <-> floating point anyway. That subset of use cases is the only set for which boost consistently is worse than the older functions- and they basically concentrated all their failure there, because their own performance results show a 20-25X SLOWER performance than using sscanf and printf for such conversions.

Google it yourself. boost::lexical_cast can handle something like 50 conversions and if you exclude the ones involving floating point #s its as good or better as the obvious alternatives (with the added advantage of being having a single API for all those operations). But bring in floats and its like the Titanic hitting an iceberg in terms of performance.

The old, dedicated str->double functions can all do 10000 parses in something like 30 ms (or better). lexical_cast takes something like 650 ms to do the same job.

Solution 16 - C++

My Problem:

  1. Locale independent string to double (decimal separator always '.')
  2. Error detection if string conversion fails

My solution (uses the Windows function _wcstod_l):

// string to convert. Note: decimal seperator is ',' here
std::wstring str = L"1,101";

// Use this for error detection
wchar_t* stopString;

// Create a locale for "C". Thus a '.' is expected as decimal separator
double dbl = _wcstod_l(str.c_str(), &stopString, _create_locale(LC_ALL, "C")); 

if (wcslen(stopString) != 0)
{
	// ... error handling ... we'll run into this because of the separator
}

HTH ... took me pretty long to get to this solution. And I still have the feeling that I don't know enough about string localization and stuff...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMax FraiView Question on Stackoverflow
Solution 1 - C++TimWView Answer on Stackoverflow
Solution 2 - C++ManuelSchneid3rView Answer on Stackoverflow
Solution 3 - C++Bill LynchView Answer on Stackoverflow
Solution 4 - C++Edison Gustavo MuenzView Answer on Stackoverflow
Solution 5 - C++DaClownView Answer on Stackoverflow
Solution 6 - C++stefanBView Answer on Stackoverflow
Solution 7 - C++emveeView Answer on Stackoverflow
Solution 8 - C++kennView Answer on Stackoverflow
Solution 9 - C++dpetekView Answer on Stackoverflow
Solution 10 - C++BSalitaView Answer on Stackoverflow
Solution 11 - C++jignatiusView Answer on Stackoverflow
Solution 12 - C++T.E.D.View Answer on Stackoverflow
Solution 13 - C++IainView Answer on Stackoverflow
Solution 14 - C++Chris TonkinsonView Answer on Stackoverflow
Solution 15 - C++Zack YezekView Answer on Stackoverflow
Solution 16 - C++anhoppeView Answer on Stackoverflow