-2

somebody can explain me why this code:

$a = 0.1;
$b = 0.2;

if ($a + $b == 0.3) {
    echo "OK";
} else {
    echo "KO";
}

returns KO?

I don't understand why the sum result is different the float 0.3, considering that:

var_dump($a + $b);

returns: float(0.3)

The only hypothesis I have is that the comparison is made between only $b and 0.3 but the doubt remains because also in this case:

if ( ($a + $b) == 0.3) {

I get KO..

suikoy
  • 2,229
  • 3
  • 19
  • 23

2 Answers2

0

This is a floating point number and the precision of this number is not fixed, if you fixed the precision than it will be okey.

Check Online

$a = 0.1;
$b = 0.2;
$c = sprintf('%.1f', ($a + $b));
if ($c  == 0.3) {
    echo "OK";
} else {
    echo "KO";
}

the result is OK now.

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
0

Use function round($a+b, 1); I have this problem in my code