我遇到了以前从未见过的事情,非常想了解发生了什么。我正在尝试将 double 舍入到小数点后 2 位并将该值转换为字符串。 Actor 阵容完成后,我的一切都变得疯狂起来。
代码如下:
void formatPercent(std::string& percent, const std::string& value, Config& config)
{
double number = boost::lexical_cast<double>(value);
if (config.total == 0)
{
std::ostringstream err;
err << "Cannot calculate percent from zero total.";
throw std::runtime_error(err.str());
}
number = (number/config.total)*100;
// Format the string to only return 2 decimals of precision
number = floor(number*100 + .5)/100;
percent = boost::lexical_cast<std::string>(number);
return;
}
我没有得到我预期的结果,所以我做了一些调查。我做了以下事情:
std::cout << std::setprecision(10) << "number = " << number << std::endl;
std::cout << "percent = " << percent << std::endl;
...并得到以下内容:
number = 30.63
percent = 30.629999999999999
我怀疑 boost 正在做一些有趣的事情。有没有人对此有任何见解?
说真的,这有多奇怪?!?我要求 double 的 10 位数精度并得到 4 位数。我要求将这 4 位数字转换为一个字符串,然后弄得一团糟。这是怎么回事?
最佳答案
十进制数30.63
不能存储在 double 类型的对象中。最接近的有效 double 值,即实际存储的值,是 8621578536647393 * 2^-48
, 用十进制表示是 30.629999999999999005240169935859739780426025390625
.
你可以看到如果你这样做 std::cout << std::setprecision(100) << "number = " << number << std::endl;
关于c++ - 将 float ( double )转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6540320/