php - Float data comparison size too large
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-06-21 10:11:00
0
4
864
$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?

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(4)
某草草

php BC high-precision function library

if(bcsub($a,$b,1)==0){
    echo '相等';
}
扔个三星炸死你
$a = 12345678912345678.8;
$b = 12345678912345678.9;
$a = (string)$a;
$b = (string)$b;
if ($a == $b) {
    echo '相等';
}
仅有的幸福

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.

洪涛
<?php
    $a = 12345678912345678.8;
    $b = 12345678912345678.9;
    if (strval($a) == strval($b)) {
        echo '相等';
    }
?>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template