Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does 0.125, formatted with 2 digits of decimal precision, show "0.12" not "0.13"?

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
}

Demo

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading