Comparing float value in PHP

PHPServer Side ProgrammingProgramming

To compare float values in PHP, the code is as follows −

Example

 Live Demo

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

Output

This will produce the following output−

2.5
3.5
Both the values aren\'t equal

Example

Let us now see another example −

 Live Demo

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

Output

This will produce the following example−

1.967
1.969
Both the values are equal!
raja
Published on 24-Dec-2019 12:08:51
Advertisements