Round Double和Cast to String

时间:2011-06-30 20:16:54

标签: c++

我认为这个问题是我之前关于将双重字符串转换为字符串的问题的后续跟进。

我有一个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)任何人都可以建议一种简洁的方法来绕圆并将其投射到一个字符串,这样我就可以得到自然想要的东西吗?

提前感谢您的帮助。 :)

4 个答案:

答案 0 :(得分:7)

Streams是C ++中常用的格式化工具。在这种情况下,字符串流将起到作用:

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

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

答案 1 :(得分:3)

我没有对此进行测试,但我相信以下内容应该有效:

string RoundedCast(double toCast, unsigned precision = 2u) {
    ostringstream result;
    result << setprecision(precision) << toCast;
    return result.str();
}

这使用setprecision操纵器来更改正在进行转换的ostringstream的精度。

答案 2 :(得分:0)

这是一个版本,无需重新发明轮子即可完成您想要的一切。

void formatPercentCommon(std::string& percent, const std::string& value, Config& config)
{   
     std::stringstream fmt(value);
     double temp;
     fmt >> temp;
     temp = (temp/config.total)*100;
     fmt.str("");
     fmt.seekp(0);
     fmt.seekg(0);
     fmt.precision( 2 );
     fmt << std::fixed << temp;
     percent = fmt.str();
}

答案 3 :(得分:0)

double value = 12.00000;

std::cout << std::to_string(value).substr(0, 5) << std::endl;

如果由于某种原因无法使用 round(),则在创建子字符串时转换为字符串会截断多余的零。前几天我遇到了这种情况。

这将显示为 12.00(不要忘记十进制字符!)