skip to Main Content

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


  1. The problem is intdiv() function requires two arguments with type int: https://www.php.net/manual/ru/function.intdiv.php

    But 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:

    intdiv((int)13.5, 10)
    

    or this way:

    intdiv(round(13.5), 10)
    

    the rest of types you specified make no sense because PHP will figure it out automatically the same way.

    Login or Signup to reply.
  2. Calling intdiv with a float argument doesn’t make much sense, and may or may not have actually been giving the result you wanted

    Taking out the superfluous casts, we have

    (13.5 + intdiv(13.5, 10) * 2.5 / 12)
    

    The 13.5 is truncated to an integer, so that becomes:

    (13.5 + intdiv(13, 10) * 2.5 / 12)
    

    It’s possible you instead expected it to round the value, giving:

    (13.5 + intdiv(14, 10) * 2.5 / 12)
    

    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:

    echo (13.5 + intdiv(19, 10) * 2.5 / 12); # 13.708333333333
    echo (13.5 + intdiv(20, 10) * 2.5 / 12); # 13.916666666667
    

    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):

    echo (13.5 + intdiv((int)floor(19.5), 10) * 2.5 / 12); # 13.708333333333
    echo (13.5 + intdiv((int)round(19.5), 10) * 2.5 / 12); # 13.916666666667
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search