Consider:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::fixed << std::setprecision(2);
std::cout << 0.125 << '\n'; // Prints "0.12"
std::cout << 0.126 << '\n'; // Prints "0.13" as expected
}
I know that floating point math isn't perfectly precise, but isn't 0.125
one of the values that actually is represented exactly? Why does it round down to "0.12"
instead of up to "0.13"
when formatting it?
CodePudding user response:
Yes, 0.125
is one of the rare floating point values that should have an exact binary representation.
Your rounding mode is probably set to round-half-to-even.