1

I have the following PHP code in which I want to compare two decimal numbers. I have read in the PHP documentation that floating point numbers have limited precision.

$a = 0.0;

for ($i = 0; $i < 10; $i++) {
    $a += 0.1;
}

var_dump($a);
echo gettype($a);

if ($a === 1.0) {
    echo "IF";
} else {
    echo "ELSE";
}

When I compare variable $a with 1.0, it always returns false, and the result will be 'ELSE'. My question is how I can get the code above working properly.

Ryan Vincent
  • 4,483
  • 7
  • 22
  • 31
user3022069
  • 377
  • 1
  • 4
  • 13

4 Answers4

1

This question has been asked before, see Compare floats in PHP.

Basically you need to calculate the difference and see if it is small enough to be acceptable as "equal".

Community
  • 1
  • 1
Erik Johansson
  • 1,646
  • 1
  • 14
  • 19
1

Try something like this:

$a = 0.0;

for ($i = 0; $i < 10; $i++) {
    $a += 0.1;


$a=number_format($a,1);
//echo gettype($a);
//echo $a.'<br>';
if (floatval($a) === 1.0)
    echo "IF";
else
    echo "ELSE";
}
sinisake
  • 11,240
  • 2
  • 19
  • 27
1

In order to make the comparison work I would truncate $a to one decimal place and format $a to a string with the required precision and compare it to "1.0".

To truncate $a I suggest reading this answer .

Or you can use $a as an integer. Them instead of incrementing by 0.1 use 1. And use 10 in the final comparison.

Community
  • 1
  • 1
Eduardo Mauro
  • 1,515
  • 1
  • 26
  • 38
1

you can just do it this way:

//just a check if it is float, than round it to 1 decimal number and compare

if(is_float($a)){
    echo 'not a float';
    $a = round($a,1);
}

and output will be 'IF'

Angel M.
  • 2,692
  • 2
  • 32
  • 43