-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..

7

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.