Home > Enterprise >  Incorrect PHP calculation
Incorrect PHP calculation

Time:12-21

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

echo (0.29*100)0  // 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))0  // result 29

CodePudding user response:

If you run that code

echo (0.29*100)0;

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-SOURCE\Testing\tst.php on line 14
Call Stack: 0.0001 393688 1. {main}() D:\PHP-SOURCE\Testing\tst.php:0
28

  • Related