Home > Back-end >  bug in php type declaration of of function parameter
bug in php type declaration of of function parameter

Time:06-08

Case: library uses code like this:

function setUnitPrice(?int $unitPrice)
    {
        return $unitPrice;
    }

and when I do like this:

$var1 = 0.58;
$var1 = $var1 * 100;
echo setUnitPrice($var1);

it comes out as 57 with php 7.2 with php 8 it shows warning of Deprecated: Implicit conversion from float 57.99999999999999 to int loses precision

I have never needed to round the float numbers in php before, can anybody explains this ? to fix this, needs to have intaval(round($var1)) but this does not make any sense

CodePudding user response:

$var1 has been declerated as float. If you do a var_dump of it, you will see. But you can do

echo setUnitPrice((integer)$var1);

CodePudding user response:

$var1 = 0.58;
$var1 = $var1 * 100;
echo setUnitPrice(round($var1));

That is my proposition

  • Related