Search code examples
phpfunctioncasting

bug in php type declaration of of function parameter


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


Solution

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

    That is my proposition