Skip to content
Advertisement

Incorrect PHP calculation

Can someone give me an explanation on why this is happening in PHP:

echo (0.29*100)%100  // result 28

It’s probably very simple but logically I do not see any explanation. Probably how PHP works in the background.

I was trying to get the first two decimal positions of a number when I ran into this case. Result should be 29 naturally.

If I round the multiplication the result is fine:

echo (round(0.29*100))%100  // result 29

Advertisement

Answer

If you run that code

echo (0.29*100)%100;

in in PHP8.1.1 the error message gives you a clue

PHP 8.1.1
Deprecated: Implicit conversion from float 28.999999999999996 to int loses precision in D:PHP-SOURCETestingtst.php on line 14
Call Stack: 0.0001 393688 1. {main}() D:PHP-SOURCETestingtst.php:0
28

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement