Home > Backend Development > PHP Tutorial > Why Doesn't Direct Float Comparison Work in PHP, and How Can We Compare Them Reliably?

Why Doesn't Direct Float Comparison Work in PHP, and How Can We Compare Them Reliably?

DDD
Release: 2025-01-03 14:27:40
Original
907 people have browsed it

Why Doesn't Direct Float Comparison Work in PHP, and How Can We Compare Them Reliably?

Handling Float Comparison in PHP

Float comparison in PHP can lead to unexpected outcomes due to the limitations of floating-point arithmetic.

Problem Instance

Consider the following code snippet:

$a = 0.17;
$b = 1 - 0.83; // 0.17
if ($a == $b) {
  echo 'a and b are same';
} else {
  echo 'a and b are not same';
}
Copy after login

In this code, $a and $b represent the same numeric value (0.17), but the comparison using == returns the result of the else condition.

Solution

Comparing floats for equality using strict comparison (==) is not reliable due to floating-point imprecision. To address this issue, consider using an acceptable difference threshold for comparison. For instance:

if (abs(($a - $b) / $b) < 0.00001) {
  echo "a and b are same";
}
Copy after login

In this code, the function abs() takes the absolute difference between $a and $b, then divides the result by $b. The comparison is done against a small threshold to account for floating-point imprecision.

Caveat

While this approach provides a reasonable solution for equality comparison of floats, it is essential to remember that floating-point values are inherently imprecise, and exact equality may not always be accurately represented.

The above is the detailed content of Why Doesn't Direct Float Comparison Work in PHP, and How Can We Compare Them Reliably?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template