php integer and float comparison mismatch

前端 未结 3 605
后悔当初
后悔当初 2020-11-29 13:49

I have the following code

$amount1 = 7299;
$amount2 = 72.9875;

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

if ($amount1 != $amount2_in_cents) {
    echo          


        
3条回答
  •  独厮守ぢ
    2020-11-29 13:56

    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

提交回复
热议问题