Home > database >  Why does C printf not round up when decimal is 16.125 but will with 16.135
Why does C printf not round up when decimal is 16.125 but will with 16.135

Time:09-14

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.

CodePudding user response:

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 (down) 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 (up) to 16.38 (the even one).

fesetround allows one to change the default.

  •  Tags:  
  • c
  • Related