1

In PHP, I was willing to compare float numbers after some operations, but it doesn't show properly. For example:

$a = 0.2;
if ( ($a - 0.2) === 0 )
    return true;
else
    return false;

It returns false. Even I tried epsilon constant, but sometimes it's incorrect. Does anyone know how to resolve this?

  • 1
    `0` is an int so the types don't match. You could `float` it, `(float)0`, or make comparison loose (for PHP >8 it would function correctly with strings as well). – user3783243 Apr 04 '21 at 11:04

5 Answers5

2

($a - 0.2) === 0 evaluates as false because === tests both value and type, and ($a - 0.2) has a floating-point type but 0 has an integer type.

If you change the expression to ($a - 0.2) === 0., it will evaluate to true because the values and types will be the same. If you change it to ($a - 0.2) == 0, it will evaluate to true because the values will be the same and == tests only the values.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • 1
    You should add a note to your answer that this only applies to the specific operation in the question. In general, float values cannot be checked for equality after opreations. Example: $a = 0.7; var_dump(($a - 0.2) == 0.5);//bool(false) – jspit Apr 05 '21 at 10:11
  • [jspit](https://stackoverflow.com/users/7271221/jspit) is right – flashdebugger Apr 06 '21 at 10:01
1

You should never compare floats for equality, due to the rounding. Some values that are finite in decimal system, are infinite in the dual system (and vice versa).

Coincidentially, 0.2 is such a dual infinite float...

0.2 decimal is 0.00110011001100110011 (repetend) binary
Honk der Hase
  • 2,459
  • 1
  • 14
  • 26
0
if (abs($a-0.2) < PHP_FLOAT_EPSILON)
LIGHT
  • 5,604
  • 10
  • 35
  • 78
  • I tried PHP_FLOAT_EPSILON as I said, but it works sometimes and it doesn't work. – flashdebugger Apr 04 '21 at 11:48
  • This is generally wrong as `PHP_FLOAT_EPSILON` is a fixed value, so using it as shown in this answer does not take into account the scale of the floating-point value. Further, [there is no general solution for comparing floating-point numbers containing rounding errors](https://stackoverflow.com/questions/21260776/how-to-compare-double-numbers/21261885#21261885). – Eric Postpischil Apr 04 '21 at 11:59
0

Just change ( ($a - 0.2) === 0 ) to ($a === 0.2) and then it works

<?php

$a = 0.2;
if ($a === 0.2)
    return true;
else
    echo false;

Your problem with ( ($a - 0.2) === 0 ) is about the different types because ($a - 0.2) is float and 0 is not so these can be the other solutions
Fix the type problem (first solution)

<?php

$a = 0.2;
if (( ($a - 0.2) === 0.0 ))
    return true;
else
    return false;

Fix the type problem (second solution)

<?php

$a = 0.2;
if (( ($a - 0.2) == 0 ))
    return true;
else
    return false;
azibom
  • 1,769
  • 1
  • 7
  • 21
0

Use this method:

$a = 0.2;
if ( abs($a - 0.2) < 0.00001 )
    return true;
else
    return false;
Taylor Lee
  • 134
  • 1
  • 9