Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printf("%.2f", (double) 12.555) return 12.55?

I was writing a program where I had to round double to second decimal place. I noticed printf("%.2f", (double) 12.555) return 12.55. However, printf("%.2f", (float) 12.555) returns 12.56. Can anyone explain why this happens?

like image 746
goops17 Avatar asked Dec 23 '22 01:12

goops17


1 Answers

12.555 is a number that is not representable precisely in binary floating point. It so happens that the closest value to 1.2555 that is representable in double precision floating point on your system is slightly less than 1.2555, and the closest value to 1.2555 that is representable in single precision floating point is slightly more than 1.2555.

Assuming the rounding mode used by the conversion is round to nearest (ties to even), which is the default in IEEE 754 standard, then the described output is to be expected.

like image 107
eerorika Avatar answered Jan 13 '23 17:01

eerorika