C++中末尾为5的浮点数舍入结果不一致问题咨询
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.075in code, the actualdoublevalue stored is slightly larger than the decimal 1.075 (something like1.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 storeddoublevalue is slightly smaller than the decimal 1.895 (around1.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, anddecimal128in 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

