我想这个问题是我之前关于将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类型数值舍入并转换为字符串,以便得到自然想要的结果?
提前感谢您的帮助。 :)