How to compare floats in PHP?

Spread the love

Sometimes, we want to compare floats in PHP.

In this article, we’ll look at how to compare floats in PHP.

How to compare floats in PHP?

To compare floats in PHP, we can get the absolute difference between the 2 numbers and see if they’re less than PHP_FLOAT_EPSILON to check if the 2 numbers are apprixoimately equal.

For instance, we write

if (abs($a - $b) < PHP_FLOAT_EPSILON) { 
  //...
}

to get the absolute difference of floats $a and $b with

abs($a - $b)

And we check if the returned difference is less than PHP_FLOAT_EPSILON.

If it’s less than PHP_FLOAT_EPSILON, than $a and $b are approximately equal.

Conclusion

To compare floats in PHP, we can get the absolute difference between the 2 numbers and see if they’re less than PHP_FLOAT_EPSILON to check if the 2 numbers are apprixoimately equal.

Leave a Reply

Your email address will not be published.