【问题标题】:Rounding a float to one decimal place then convert to a string [duplicate]将浮点数舍入到小数点后一位,然后转换为字符串 [重复]
【发布时间】:2015-12-19 23:12:23
【问题描述】:

我有这个:

#include <iostream>
#include <iomanip> 

std::string ExampleInstance::RoundNumber(float result) {

    std::string RoundResult;

    std::cout << std::fixed << std::showpoint;
    std::cout << std::setprecision(1);
    std::cout << result << std::endl;

    RoundResult = std::to_string(result);
    return RoundResult;
}

我想给这个方法传递一个浮点数,将其四舍五入到小数点后一位,将其转换为字符串,然后返回。目前这对号码没有任何作用。

setPrecision 会更有效吗?我是 C++ 新手。

【问题讨论】:

    标签: c++ rounding tostring floating-accuracy


    【解决方案1】:

    您可以为此目的使用ostringstream。不要忘记包括&lt;sstream&gt;

    代码 sn-p:

    string RoundNumber(float result)
    {
        std::ostringstream out;
        out<<std::setprecision(1)<<std::fixed<<std::showpoint<< result;
        std::string RoundResult =  out.str();
        return RoundResult;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 2011-02-18
      • 2023-03-25
      • 1970-01-01
      • 2012-11-11
      相关资源
      最近更新 更多