简体   繁体   English

将lexical cast string提升一倍

[英]boost lexical cast string to double

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. 我正在使用gcc4编译器,我很受限制地使用gcc4。

I want to convert std::string to double. 我想将std :: string转换为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. 顺便说一句,我也试过atof ,我仍然有同样的问题。 Is there any way to use istringstream with setprecission(2) to get the correct value shown by aAmount ? 有没有办法使用istringstream setprecission(2) istringstream来获得aAmount显示的正确值?

Due to the nature of floating point values, 22.050000000000001 is the closest value to 22.05 that can be stored. 由于浮点值的性质,22.050000000000001是可以存储的最接近22.05的值。 The same would occure if you simply tried to store 22.05 in a double and then print it. 如果您只是尝试将22.05存储在一个double中然后打印它,则会发生同样的情况。

You should set the precision on the output stream if you want to print 22.05. 如果要打印22.05,则应在输出流上设置精度。 Alternatively you could investigate a rational number library (for example, Boost.Rational ). 或者,您可以调查有理数字库(例如, Boost.Rational )。 This would be able to store the value 22.05 precisely, unlike a double (or float). 与double(或float)不同,这将能够精确地存储值22.05。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM