1

I was doing some coding and suddenly wondered with a strange behavior of floor(). The piece of line that caused error is mentioned below:

printf("%f",floor(310.96*100));

and the output was 31095.0000.

Why is this happening?

Mat
  • 202,337
  • 40
  • 393
  • 406
jeninjames
  • 128
  • 7

2 Answers2

1

This is a typical floating point issue. The constant value 310.96 is not equally representable as a float number. Instead the closest float value representation is 310.9599914550781.

You can try out your self here. Multipled that by 100 and truncated with floor() results in your 31095.0000

Community
  • 1
  • 1
Frank Bollack
  • 24,478
  • 5
  • 49
  • 58
  • but why the same is not happening for 310.95 or 310.97?? – jeninjames Sep 13 '13 at 11:03
  • temp = 310.96*100; floor(temp); output is 31096......why it is not happening here? – jeninjames Sep 13 '13 at 11:05
  • If you check on the site I linked you can see that the closest floating point representation of `310.95` is `310.95001220703125` which greater than `310.95` and so `floor()` on the result of multiplication will (in this case) lead to the expected value. The general rule of thumb is, to not rely on exact flaoting point values but to understand their limitations and compensate for that, using ranges or appropriate rounding mechanisms – Frank Bollack Sep 13 '13 at 13:49
0

Floating point numbers are not 100% exact 310.96*100 might result in 31095.99999999... hence your result, see also this

Community
  • 1
  • 1
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110