Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php integer and float comparison mismatch

Tags:

php

I have the following code

$amount1 = 7299;
$amount2 = 72.9875;

$amount2_in_cents = round($amount2, 2) * 100;

if ($amount1 != $amount2_in_cents) {
    echo "Amount $amount1 != $amount2_in_cents\n";

    var_dump($amount1);
    var_dump($amount2_in_cents);    

} else {
    echo "Amounts matched";
}

and this is the output

Amount 7299 != 7299
int(7299)
float(7299)

Now I realise that floats and int are different, but given the rounding i would have expected the two values to match. And I have solved it by casting to int.

So my question is why does this comparison not work as i would have expected (both values matching)?

like image 348
bumperbox Avatar asked Nov 28 '22 07:11

bumperbox


1 Answers

Notice the big red warning in the PHP Manual!

Never expect anything when comparing floats. The result of round, even if the precision is 0, is still a float. In your particular case it happened that the result was a little bigger than expected, so casting to int resulted in equality, but for other numbers it might as well happen for it to be a little smaller than expected and casting to int won't round it, but truncate it, so you can't use casting as a workaround. (As a note, a better solution than yours would be casting to string :), but still a lousy option.)

If you need to work with amounts of money always use the BC Math extension.

For rounding with BC Math you can use this technique:

$x = '211.9452';
$x = bcadd($x, '0.005', 2);

Good luck,
Alin

like image 90
Alin Purcaru Avatar answered Dec 05 '22 22:12

Alin Purcaru