c++ - 将 float ( double )转换为字符串

标签 c++ boost

我遇到了以前从未见过的事情,非常想了解发生了什么。我正在尝试将 double 舍入到小数点后 2 位并将该值转换为字符串。 Actor 阵容完成后,我的一切都变得疯狂起来。

代码如下:

void formatPercent(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;
}

我没有得到我预期的结果,所以我做了一些调查。我做了以下事情:

std::cout << std::setprecision(10) << "number = " << number << std::endl;
std::cout << "percent = " << percent << std::endl;

...并得到以下内容:

number = 30.63
percent = 30.629999999999999

我怀疑 boost 正在做一些有趣的事情。有没有人对此有任何见解?

说真的,这有多奇怪?!?我要求 double 的 10 位数精度并得到 4 位数。我要求将这 4 位数字转换为一个字符串,然后弄得一团糟。这是怎么回事?

最佳答案

十进制数30.63不能存储在 double 类型的对象中。最接近的有效 double 值,即实际存储的值,是 8621578536647393 * 2^-48 , 用十进制表示是 30.629999999999999005240169935859739780426025390625 .

你可以看到如果你这样做 std::cout << std::setprecision(100) << "number = " << number << std::endl;

关于c++ - 将 float ( double )转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6540320/

相关文章:

c++ - 从 vector<string> 中查找字符串的第一次出现

c++ - SFINAE 不可解的重载

c++ - 在 netbeans IDE 中将 "media"文件添加到 c/c++ 项目的适当方法

c++ - boost hana index_if 和 type

c++ - 复制 boost::program_options::parsed_options

c++ - OS X Lion C++11、Boost 和其他问题

c++ - 如果当前对象是 r 值引用,是否可以返回当前对象?

c++ - Qt中的数据库连接池

c++ - 转换 Eigen 矩阵类型时,错误 : expected primary-expression before ‘float’

c++ - 将 Mysql 阻塞 API 与 Boost::asio 结合使用