You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中末尾为5的浮点数舍入结果不一致问题咨询

Why 1.075 rounds to 1.08 but 1.895 rounds to 1.89 in C++?

Hey there, this is such a common gotcha with floating-point numbers—let me break it down for you!

The core issue here is that decimal fractions like 1.075 and 1.895 can’t always be represented exactly as binary floating-point values (the format C++ uses for float and double). Binary floats store numbers as sums of powers of 2, so any decimal fraction that doesn’t cleanly translate to this format gets stored as an approximation.

Let’s dig into your two examples:

  • When you write 1.075 in code, the actual double value stored is slightly larger than the decimal 1.075 (something like 1.0750000000000000666...). When rounding to two decimal places, this tiny extra push puts it just over the threshold to round up to 1.08.
  • For 1.895, the stored double value is slightly smaller than the decimal 1.895 (around 1.8949999999999999023...). Even though the decimal looks like it should round up, the stored value is just under the threshold, so it rounds down to 1.89.

You can confirm this yourself by printing the values with high precision:

#include <iostream>
#include <iomanip>

int main() {
    double num1 = 1.075;
    double num2 = 1.895;
    std::cout << std::setprecision(20) << num1 << "\n";
    std::cout << std::setprecision(20) << num2 << "\n";
    return 0;
}

Running this will show you the exact approximate values stored in memory, which directly explains the confusing rounding behavior.

How to handle this properly?

If you need precise decimal rounding (like for currency or financial calculations), avoid binary floats entirely. Instead:

  • Use decimal floating-point types: C++17 introduced std::decimal::decimal32, decimal64, and decimal128 in the <decimal> header (note: compiler support varies).
  • Store values as integers: For example, represent dollars as cents (so $1.89 becomes 189 cents) and handle rounding with integer arithmetic.
  • Use a dedicated decimal arithmetic library for full control over precision and rounding rules.

The std::round function and other C++ rounding utilities aren’t "broken"—they work exactly as intended based on the actual binary value stored in memory. The confusion just comes from expecting decimal behavior from a binary system!

内容的提问来源于stack exchange,提问作者Eric Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:54:34