1
echo (int)(3980 / 100 * 50); 
echo PHP_EOL;
echo (3980 / 100 * 50);

output

1989
1990

can someone explain this phenomenal for me?

  • 2
    `floor(3980 / 100 * 50)` give `1989`. It should be a rounding thing internally. – nice_dev Jul 21 '21 at 09:55
  • but `3980 / 100 * 50` should gave out exact 1990 right? and why when not rounding is correct – Phúc Hậu Trần Jul 21 '21 at 10:43
  • [This](https://3v4l.org/RX7dO) is a more interesting example, I think. I don’t know what changed in PHP regarding floating point numbers, but I think a standard rule is “don’t rely on the string cast of a float”. The int cast at least makes sense, since PHP rounds towards zero. – Chris Haas Jul 21 '21 at 11:36

1 Answers1

2

This is because of how floating point numbers are represented internally in binary IEEE 754

One may think (3980 / 100) will be 39.8

But infact, it will be represented exactly like 39.799999237060546875 and multiplying it by 50 it will be 1989.999961853

Now (int)1989.999961853.. you guessed it 1989

Rain
  • 3,416
  • 3
  • 24
  • 40
  • 2
    Yes, `(int)` is the same as `floor()` in this case. If this question is meant beyond understanding and there is an actual math error you must fix: [BCMath](https://www.php.net/manual/en/book.bc.php) or [PHP-Decimal](http://php-decimal.io/#introduction) – Peter Krebs Jul 22 '21 at 13:31