Bogdan Burym
Bogdan Burym

Reputation: 5512

Compare two numbers in PHP

In my application I have a procedure which is related with financial balance modification, and, so, it is wrapped in a transaction.

And the end of the operation, just before committing the transaction, I have a small check - to make sure balance was modified correctly.

   public function setBalance($amount) {
       // ......
       // Updating balance code, nothing worst attention
       // ......

       $balance = $this->getBalance(false);

       if ($amount != $balance) {
           throw new Exception('Error updating balance! ' . $balance . " instead of " . $amount);
       }

This easy code throws the exception. It says 386.57 is not equal 386.57. Really.

I have tried to check what's the difference using my favorite var_dump and die.

    var_dump($balance - $amount);
    die();

Output is even more wonderfull:

    float(-2.8421709430404E-13)

Both numbers $balance and $amount are float.

Can someone explain this strange behavior and why is it happening? Is there some mistake?

Upvotes: 0

Views: 89

Answers (1)

KIKO Software
KIKO Software

Reputation: 16688

This is normal when using floats. Try use this code:

if (abs($amount-$balance) > 0.001) {
   throw new Exception('Error updating balance! ' . $balance . " instead of " . $amount);
}

If you're caught out by this, remember to properly round as well. This is NOT easy. When to round, and how to round, is done differently by a lot of people. Note that the PHP round() function now allows you to choose the type of rounding. Like this:

round($Value,2,PHP_ROUND_HALF_EVEN);

Upvotes: 2

Related Questions