我想這個問題是我之前關於將一個double轉換爲一個字符串的問題的後續。Round 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;
}
不幸的是,演員捕捉到「未被包圍」的值。 (即數字= 30.63,百分比= 30.629999999999)任何人都可以提出一個乾淨的方式來圓化一個雙精度並將其轉換爲一個字符串,這樣我就能得到一個自然需要的東西?
在此先感謝您的幫助。 :)
非常感謝!我真的不想不得不使用snprintf()創建一個臨時字符數組和格式。 :) – Rico