search

Home  >  Q&A  >  body text

php - Float data comparison size too large

$a = 12345678912345678.8;
$b = 12345678912345678.9;

Just these two different numbers, if($a == $b){echo 'equal';} results in output of 'equal'. I know it is too large and exceeds its range. The result of outputting $a alone is: 1.2345678912346E 16 hexadecimal. What is the best way to compare such large data?

曾经蜡笔没有小新曾经蜡笔没有小新2741 days ago881

reply all(4)I'll reply

  • 某草草

    某草草2017-06-21 10:13:00

    php BC high-precision function library

    if(bcsub($a,$b,1)==0){
        echo '相等';
    }

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-21 10:13:00

    $a = 12345678912345678.8;
    $b = 12345678912345678.9;
    $a = (string)$a;
    $b = (string)$b;
    if ($a == $b) {
        echo '相等';
    }

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-21 10:13:00

    After testing on my own computer, when the length exceeds 14 characters, PHP will fail. Different systems and different PHP versions will have different lengths.

    Related information official manual

    Method 1:

    $a = '12345678912345678.6';
    $b = '12345678912345678.9';
    if($a == $b) {
        echo 1;
    }

    Method 2:
    Only the following ideas are provided here

    If you want to compare directly through floating points, there is no way.

    1. First separated by

    2. Get the number of digits in the integer part, compare the length, and then compare the size.

    3. If the integer parts are equal, then compare the decimal parts.

    Tip: Considering that the number is infinite, you should also pay attention to the length of the number after separation. If it is longer, separate it again.

    reply
    0
  • PHP中文网

    PHP中文网2017-06-21 10:13:00

    <?php
        $a = 12345678912345678.8;
        $b = 12345678912345678.9;
        if (strval($a) == strval($b)) {
            echo '相等';
        }
    ?>

    reply
    0
  • Cancelreply