0

Perl's floor function is giving me unexpected results.

floor(13320) = 13320, but floor(133.20 * 100) = 13319. I'd think both of those would get the same result. Why is this happening?

use POSIX;

print floor(133.20);       # 133, as expected
print floor(13320);        # 13320, as expected
print floor(133.20 * 100); # 13319?
Bruce
  • 1,542
  • 13
  • 17
Tyler S
  • 11
  • 3
  • 2
    `printf("%.20f",133.20*100)` for enlightenment – mob Sep 22 '20 at 23:37
  • 1
    2/10 is a periodic number in binary, just like 1/3 is a periodic number in decimal. As such, 2/10 can't be accurately represented by a floating-point number. (That would require infinite storage.) So instead of `133.20`, you end up with `133.19999999999998863131622783839702606201171875` – ikegami Sep 23 '20 at 00:54
  • [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – brian d foy Sep 23 '20 at 16:27

0 Answers0