Open In App

Comparing float value in PHP

Last Updated : 11 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In PHP, the size of a floating values is platform-dependent. Due to internal representation of floating point numbers, there might be unexpected output while performing or testing floating point values for equality. For example, see the following program.

PHP




<?php
 
// Declare valuable and initialize it
$value1 = 8 - 6.4;
$value2 = 1.6;
 
// Compare the values
if($value1 == $value2) {
    echo 'True';
}
else {
    echo 'False';
}
 
?>


Output: 

False

 

Explanation: The output of this code is False which is very unpredictable but in PHP the value1 is not exactly 1.6 i.e it is coming from the difference between 8 and 6.4 which actually turned out to be 1.599999 that is why this statement turned out to be false.

How to resolve above problem? 
Method 1 : For equality testing in floating point values, use the machine epsilon or we can call it smallest difference in calculation in computer systems.

Program 1:  

PHP




<?php
// PHP program to compare floating values
 
// Declare variable and initializing
// it by floating value
$value1 = 1.23456789;
$value2 = 1.23456780;
$epsilon = 0.00001;
 
// Use absolute difference and compare values
if(abs($value1 - $value2) < $epsilon) {
    echo "True";
}
else {
    echo "False";
}
 
?>


Output: 

True

 

Explanation: In this code use two floating point numbers value1 and value2 along with epsilon. Now take the absolute difference of values (value1 and value2) by using the predefined function named as abs(). This code will give the absolute value but the question is why we are taking the absolute values. You can see that both the values having same digits after decimal upto precision value 7. Which is very difficult for the system to analyze the comparison. 

Method 2 : We can use round function in PHP.  

PHP




<?php
// PHP program to compare floating values
 
// Declare valuable and initialize it
$value1 = 8 - 6.4;
$value2 = 1.6;
 
// Use round function to round off the
// floating value upto two decimal place
// and then compare it.
var_dump(round($value1, 2) == round($value2, 2));
 
?>


Output: 

bool(true)

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads