Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

php integer and float comparison mismatch

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
";

    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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...