I was using below formula in PHP. It was working fine till PHP 7.4. Now I have upgraded to PHP 8.1 and it’s giving error.
<?php
echo ((float)13.5 + intdiv((float)13.5, (int)10) * (float)2.5 / (int)12);
I’m getting error Exception: Deprecated Functionality: Implicit conversion from float 13.5 to int loses precision
How can I solve this? What is the reason for this error?
2
Answers
The problem is
intdiv()
function requires two arguments with typeint
: https://www.php.net/manual/ru/function.intdiv.phpBut you’re passing
float
variable as the 1st argument, which causes implicit type conversion.You should somehow convert your float variable into
int
before passing into the function.This way:
or this way:
the rest of types you specified make no sense because PHP will figure it out automatically the same way.
Calling
intdiv
with afloat
argument doesn’t make much sense, and may or may not have actually been giving the result you wantedTaking out the superfluous casts, we have
The
13.5
is truncated to an integer, so that becomes:It’s possible you instead expected it to round the value, giving:
For the example of 13.5, the answer is the same, but assuming that’s actually a variable, it would give different examples for 19.5, for instance:
To make it explicit, you could use the floor or round functions on the float first, then cast it to an int (since the result of rounding is still technically a float):