php How to Compare Two Floating Point Numbers for Equality
- 2021-11-24 00:56:36
- OfStack
Preface
This article mainly introduces how to compare floating-point numbers with php. The following words are not much to say. Let's take a look at the detailed introduction
Look at the following code, and the addition result of 0.9 +0.1 is compared with 1
<?php
$a = 0.9;
$b = 0.1;
$total = $a + $b;
var_dump($total);
if (1 == $total) {
echo "true";
} else {
echo "false";
}
echo "\n";
if (1.0 == $total) {
echo "true";
} else {
echo "false";
}
?>
The printed result is:
float(1)
true
true
Looking at the following code, the addition of 0.6 +0.1 +0.1 +0.1 +0.1 is compared with 1
<?php
$a = 0.6;
$b = 0.1;
$c = 0.1;
$d = 0.1;
$e = 0.1;
$total = $a + $b + $c + $d + $e;
var_dump($total);
if (1 == $total) {
echo "true";
} else {
echo "false";
}
echo "\n";
if (1.0 == $total) {
echo "true";
} else {
echo "false";
}
?>
The printed result is:
float(1)
false
false
Why are these two pieces of code different? Print printf ("%. 20f\ n", $total) in the form of 20-bit precision respectively; The results are as follows:
1.00000000000000000000
0.99999999999999988898
This problem occurs because floating-point calculation involves precision.
As for the floating point number in php, the official manual has relevant explanations
Look at the tips on floating-point numbers in the official manual, as shown in the following figure. It says never compare whether two floating-point numbers are equal
So is there any way to compare whether two floating-point numbers are equal?
Method 1.
Look at the following code example
<?php
$a = 0.6;
$b = 0.1;
$c = 0.1;
$d = 0.1;
$e = 0.1;
$epsilon = 0.00001;
$total = $a + $b + $c + $d + $e;
if(abs($total-1) < $epsilon) {
echo "true";
} else {
echo "false";
}
echo "\n";
if(abs($total-1.0) < $epsilon) {
echo "true";
} else {
echo "false";
}
?>
The result output is:
true
true
Method 2.
<?php
$a = 0.6;
$b = 0.1;
$c = 0.1;
$d = 0.1;
$e = 0.1;
$total = $a + $b + $c + $d + $e;
if(1.0 == round($total, 5)) {
echo "true";
} else {
echo "false";
}
?>
The result output is:
true
Summarize