0

With this code:

<?php
echo (int)(130.98 * 100) . "\n";
echo (int)(30.98 * 100) . "\n";
echo (int)(0.98 * 100) . "\n";

I get output:

13097
3098
98

Why is the first result 13097 ???

adminko
  • 73
  • 1
  • 7
  • 1
    because floating point. it's internally something like 13097,999999999999... and casting it to int just truncates after the comma. that's just how computers process numbers. use `round()` instead. and if you want, you can [read up](http://floating-point-gui.de/formats/fp/) on further information – Franz Gleichmann Dec 24 '16 at 11:45
  • http://floating-point-gui.de/ –  Dec 24 '16 at 11:49
  • Yes, thank you, but why only first result is bad? – adminko Dec 24 '16 at 11:51
  • @adminko because the second could be along the lines of 3098.0000000[...]1, which is *not exactly* 3098, but will be truncated to it when cast to int. – Franz Gleichmann Dec 24 '16 at 11:53
  • 1
    Look at your numbers with more digits after the dot. For `130.98` you get a binary representation that has as closest decimal expression `130.979999999999989768184605054557`. For `130.98*100` you get `13097.999999999998181010596454143524`. `30.98` has 3 bit more for the digits after the decimal dot and thus gets the closer floating point number `30.980000000000000426325641456060`. Multiplication with 100 gets here rounded to the integer, even before the truncation during type conversion. – Lutz Lehmann Dec 24 '16 at 18:37

0 Answers0