Comparing float value in PHP

Comparing float values in PHP requires special attention due to floating-point precision issues. Direct equality comparison may not work as expected for values that appear equal but have tiny precision differences.

Basic Float Comparison

The simplest approach uses direct comparison operators ?

<?php
   $a = 2.5;
   $b = 3.5;
   echo $a;
   echo "<br>$b";
   if($a == $b) {
      echo "\nBoth the values are equal!";
   } else {
      echo "\nBoth the values aren't equal";
   }
?>
2.5
3.5
Both the values aren't equal

Using round() for Precision Control

When comparing floats with similar values, use round() to control decimal precision ?

<?php
   $a = 1.967;
   $b = 1.969;
   echo $a;
   echo "<br>$b";
   if((round($a, 2)) == (round($b, 2))) {
      echo "\nBoth the values are equal!";
   } else {
      echo "\nBoth the values aren't equal";
   }
?>
1.967
1.969
Both the values are equal!

Using abs() for Tolerance-Based Comparison

For precise floating-point comparison, use absolute difference with a tolerance value ?

<?php
   $a = 0.1 + 0.2;
   $b = 0.3;
   $tolerance = 0.00001;
   
   echo "a = $a<br>";
   echo "b = $b<br>";
   
   if(abs($a - $b) < $tolerance) {
      echo "Values are equal within tolerance!";
   } else {
      echo "Values are not equal";
   }
?>
a = 0.3
b = 0.3
Values are equal within tolerance!

Comparison Methods

Method Use Case Precision Control
== Simple comparisons No
round() Fixed decimal places Yes
abs() Floating-point precision issues Custom tolerance

Conclusion

Use direct comparison for simple cases, round() for fixed precision, and abs() with tolerance for accurate floating-point comparisons. The tolerance method is recommended for critical calculations.

Updated on: 2026-03-15T08:17:30+05:30

820 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements