gpt4 book ai didi

c++ - 舍入 Double 并转换为字符串

转载 作者:太空狗 更新时间:2023-10-29 23:42:01 25 4
gpt4 key购买 nike

我想这个问题是我之前关于将 double 类型转换为字符串的问题的后续问题。

我有一个 API,其中提供了一个代表数字的字符串。我需要将这个数字舍入到 2 位小数的精度并将其作为字符串返回。我的尝试如下:

void formatPercentCommon(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;
}

不幸的是,转换捕获了“未舍入”的值。 (即 number = 30.63,percent = 30.629999999999)谁能提出一种干净的方法来舍入 double 并将其转换为字符串,以便我得到自然想要的东西?

在此先感谢您的帮助。 :)

最佳答案

流是 C++ 中常用的格式化工具。在这种情况下,stringstream 可以解决问题:

std::ostringstream ss;
ss << std::fixed << std::setprecision(2) << number;
percent = ss.str();

您可能已经熟悉了上一篇文章中的 setprecisionfixed这里用于使精度影响小数点后的位数,而不是为整数设置有效位数。

关于c++ - 舍入 Double 并转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6540606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com