Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Comparison of floating point values in PHP.
In PHP, testing floating point values for equality is problematic because of how floating point numbers are represented internally. Values that appear identical may not actually be equal due to precision limitations. This article demonstrates the issue and provides solutions for reliable floating point comparison.
The Problem
Let's examine this issue with a simple example −
<?php
$a = 0.14;
$b = 1 - 0.86; // Should be 0.14
if($a == $b) {
echo 'a and b are same';
}
else {
echo 'a and b are not same';
}
?>
a and b are not same
The else condition executes even though both variables should equal 0.14. This occurs because floating point arithmetic can introduce tiny rounding errors that make direct equality comparison unreliable.
Solution 1: Using Epsilon Comparison
Compare the absolute difference between two floating point values against a small tolerance value (epsilon) −
<?php
$val1 = 2.183459;
$val2 = 2.183450;
$epsilon = 0.00001;
if(abs($val1 - $val2) < $epsilon) {
echo "Values are equal within tolerance";
}
else {
echo "Values are different";
}
?>
Values are equal within tolerance
The abs() function calculates the absolute difference, and we check if it's smaller than our epsilon value. This method considers values "equal" if they differ by less than the specified tolerance.
Solution 2: Using round() Function
Round both values to the same precision before comparison −
<?php
$val1 = 9 - 6.2; // Results in 2.8 (with potential precision issues)
$val2 = 2.8;
var_dump(round($val1, 2) == round($val2, 2));
?>
bool(true)
The round() function eliminates precision errors by rounding both values to a specified number of decimal places before comparison.
Comparison of Methods
| Method | Use Case | Precision Control |
|---|---|---|
| Epsilon comparison | Scientific calculations | Flexible tolerance |
| round() function | Financial/display values | Fixed decimal places |
Conclusion
Never use direct equality (==) for floating point comparisons. Use epsilon comparison for flexible tolerance or round() for fixed precision. Choose the method based on your application's requirements for accuracy and precision.
