$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?
某草草2017-06-21 10:13:00
php BC high-precision function library
if(bcsub($a,$b,1)==0){
echo '相等';
}
扔个三星炸死你2017-06-21 10:13:00
$a = 12345678912345678.8;
$b = 12345678912345678.9;
$a = (string)$a;
$b = (string)$b;
if ($a == $b) {
echo '相等';
}
仅有的幸福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.
First separated by
Get the number of digits in the integer part, compare the length, and then compare the size.
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中文网2017-06-21 10:13:00
<?php
$a = 12345678912345678.8;
$b = 12345678912345678.9;
if (strval($a) == strval($b)) {
echo '相等';
}
?>