【问题标题】:Round Double and Cast to StringRound Double 和 Cast to String
【发布时间】:2011-06-30 20:16:54
【问题描述】:

我想这个问题是我之前关于将双精度转换为字符串的问题的后续问题。

我有一个 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)任何人都可以提出一种干净的方法来舍入双精度并将其转换为字符串,以便我得到自然想要的东西吗?

提前感谢您的帮助。 :)

【问题讨论】:

    标签: c++


    【解决方案1】:
    double value = 12.00000;
    
    std::cout << std::to_string(value).substr(0, 5) << std::endl;
    

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

    这将显示为 12.00(不要忘记小数字符!)

    【讨论】:

    • 好的,谢谢。好久没上这个网站了,忘记使用代码编辑器了。下次一定记得格式化!
    • 我使用了类似res = res.substr(0, res.length() - 5); 的东西来去掉多余的零
    【解决方案2】:

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

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

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

    【讨论】:

    • 非常感谢!我真的不想求助于使用 snprintf() 创建一个临时字符数组和格式。 :)
    【解决方案3】:

    我没有对此进行测试,但我相信以下应该可以工作:

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

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

    【讨论】:

      【解决方案4】:

      这是一个无需重新发明轮子即可满足您所有需求的版本。

      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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-17
        • 2011-10-19
        • 1970-01-01
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多