boost lexical cast string to double

user1400995 picture user1400995 · Aug 6, 2013 · Viewed 8.4k times · Source

I am facing a conversion issue for which I'd like your help. I'm using gcc4 compiler and I am quite restricted to use gcc4.

I want to convert std::string to double.

std::string aQuantity = aRate.getQuantity();
std::string aAmount = aRate.getAmount(); 

// aAmount = "22.05"

double dQuantity = boost::lexical_cast<double>(aQuantity);
double dAmount = boost::lexical_cast<double> (aAmount);

// dAmount =  22.050000000000001

By the way, I also tried atof and I still have the same issue. Is there any way to use istringstream with setprecission(2) to get the correct value shown by aAmount?

Answer

dunc123 picture dunc123 · Aug 6, 2013

Due to the nature of floating point values, 22.050000000000001 is the closest value to 22.05 that can be stored. The same would occure if you simply tried to store 22.05 in a double and then print it.

You should set the precision on the output stream if you want to print 22.05. Alternatively you could investigate a rational number library (for example, Boost.Rational). This would be able to store the value 22.05 precisely, unlike a double (or float).