简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM