Comparison of floating point values in PHP.


In PHP, testing floating point values for equality is problematic, because PHP is failing when checking if one floating point number is equal to another. Despite the fact floating point numbers seems to have the same value do not need to actually be identical. So in this article will demonstrate the problem we are facing in comparison of Floating-Point Numbers and different procedures to avoid this problem.

Example

Let's test this with a simple example:

<?php
   $a = 0.14;
   $b = 1 - 0.86; //0.14
   if($a == $b ){
      echo 'a and b are same';
   }
   else {
      echo 'a and b are not same';
   }
?>

output:

a and b are not same.

Explanation:

In this code, the else condition is executed instead of the if condition, even though $a and $b are the same. It is due to the characteristic of floating-point values that the way they were represented internally. Let's discuss different cases in PHP to avoid this problem in real time.

Case1:

Demonstrate a comparison of floating point values by using the smallest difference in the calculation in computer systems.

Example:

<?php
   $val1 = 2.183459;
   $val2 = 2.183450;
   $epsilon = 0.00001;
   if(abs($val1 - $val2) < $epsilon) {
      echo "True";
   }
   else {
      echo "False";
   }
?>

Output:

True

Explanation:

Here we are using two floating point variables val1 and val2 alongside epsilon. Then we take the absolute difference of variables (val1 and val2) by utilizing the native function named as abs(). This code will give us the absolute value but the question is why we are taking the absolute values? The answer is we can see that both the values having the same digits after decimal up to precision value 5, Which is hard for PHP to analyze the comparison.

Case 2:

Use of round() function.

<?php
   $val1 = 9 - 6.2;
   $val2 = 1.8;
   var_dump(round($val1, 2) == round($val2, 2));
?>

Output:

bool(true)

Explanation:

Here we are using two floating point variables val1 and val2. Then we are using the predefined function named as round () which is round off floating values up to two decimal places and then compare it. Here We are using the predefined round() function to get our expected result in the correct way.

Updated on: 31-Dec-2019

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements