search

Home  >  Q&A  >  body text

Implicit conversion from float (number) to int loses precision

I have used this formula before php 8.1

<?php
$number = 0;
echo log10(abs($number)) / 3 | 0;

echo PHP_EOL;

$number = 100;
echo log10(abs($number)) / 3 | 0;

echo PHP_EOL;
    
$number = 1100;
echo log10(abs($number)) / 3 | 0;

echo PHP_EOL;
    
$number = 10000000;
echo log10(abs($number)) / 3 | 0;
?>

It worked fine but now after upgrading I keep getting these errors

Deprecated: Implicit conversion from float -INF to int loses precision

Deprecated: Implicit conversion from float 0.6666666666666666 to int loses precision

Deprecated: Implicit conversion from float 1.0137975617194084 to int loses precision

Deprecated: Implicit conversion from float 2.3333333333333335 to int loses precision

I can't find or understand from the 8.1 documentation why this is happening now

P粉449281068P粉449281068444 days ago923

reply all(2)I'll reply

  • P粉043295337

    P粉0432953372023-10-22 12:07:10

    // Implicit variant
    $number= "2";
    $calc = 2 + $number;
    
    // Cast variant
    $number = "2";
    $calc= 2 + (int) $number;
    
    // Explicit variant
    $number = "2";
    $calc = 2 + intval($number);
    
    // Everything is good variant ^^
    $number = 2;
    $calc = 2 + $number;

    reply
    0
  • P粉211600174

    P粉2116001742023-10-22 10:41:26

    When you perform a bitwise OR operation via the | operator, you get an implicit conversion to an integer. This is a...weird...way to convert to an integer. To avoid the warning, just cast explicitly.

    Implicit:

    echo log10(abs($number)) / 3 | 0;

    Explicitly pass the function:

    echo intval(log10(abs($number)) / 3);

    Or via cast:

    echo (int) (log10(abs($number)) / 3);

    reply
    0
  • Cancelreply