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 C printf not round up when decimal is 16.125 but will with 16.135

I am using C printf to print doubles and found the rounding is inconsistent. Sometimes it will not round up with certain values.

double t = 16.125;
printf("%-10.2lf", t);

This prints 16.12. I thought it would round up to 16.13.

double t = 16.135;
printf("%-10.2lf", t);

This prints 16.14. This is what I thought would happen for all cases.

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 :

The default rounding behaviour is round-half-to-even.

This means:

  • 16.125 is exactly halfway between 16.12 and 16.13, so it rounds to 16.12 (the even one).

  • 16.135 can’t be exactly represented by a floating-point number. On my system, it’s 16.135000000000001563194018672220408916473388671875. This number is closer to 16.14 than to 16.12, so it rounds to 16.14.

  • 16.375 is exactly halfway between 16.37 and 16.38, so it rounds to 16.38 (the even one).

fesetround allows one to change the default.

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