$ printf "%0.2f\n" 41.495
41.49
$ printf "%0.2f\n" 41.485
41.49
$ printf "%0.2f\n" 41.475
41.47
$ printf "%0.2f\n" 41.465
41.47
$ printf "%0.2f\n" 41.455
41.46
$ printf "%0.2f\n" 41.445
41.44
$ printf "%0.2f\n" 41.435
41.44
$ printf "%0.2f\n" 41.425
41.42
$ printf "%0.2f\n" 41.415
41.42
$ printf "%0.2f\n" 41.405
41.40
Why are the numbers with an uneven number as the second decimal not correctly rounded and even ones are? Additionally what is wrong with .445 that it never gets rounded?
It has to do with floating-point, but not with double-precision.
When you write
on your system,
printffirst rounds41.495to the closest x87 80-bit floating-point number[1]. How does that work? First write 41.495 in binary:(the separated groups repeat ad infinitum). Now we round this number to have 64 binary digits:
This is the number that is actually formatted by printf. Written in decimal, it is exactly:
as you can see, it is just a little bit less than 41.495, so when printf rounds it to two fractional digits, it rounds down, and
41.49is printed.Now look at 41.485; after rounding to 64 binary digits, we get the value:
which is just a little bit bigger than 41.485, so printf rounds it up.
On my system, there is a warning about this in the printf manage: