PHP整数和浮点数比较不匹配 [英] php integer and float comparison mismatch

查看:77
本文介绍了PHP整数和浮点数比较不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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

这是输出

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

现在我意识到float和int是不同的,但是考虑到四舍五入,我希望这两个值能够匹配.我已经通过强制转换为int来解决了这个问题.

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

推荐答案

请注意红色大警告". types.float.php> PHP手册!

Notice the big red warning in the PHP Manual!

比较浮点数时不要期望任何东西.即使精度为0,舍入的结果仍然是浮点数.在您的特定情况下,碰巧结果比预期的要大一点,因此强制转换为int会导致相等,但对于其他数字,它也可能会比预期的小一点,并且强制转换为int不会舍入它,但是要截断它,因此您不能使用强制转换作为解决方法. (请注意,比您的解决方案更好的解决方案是强制转换为string :),但仍然是一个糟糕的选择.)

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

如果您需要花很多钱,请始终使用 BC Math扩展.

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

要使用BC Math进行四舍五入,您可以使用以下技术:

For rounding with BC Math you can use this technique:

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

祝你好运,
阿林

Good luck,
Alin

这篇关于PHP整数和浮点数比较不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆