The accuracy of PHP float calculate

2019-01-02 21:49发布

问题:

$fooValue = 100.68;
$cowValue = 100.67;

$diffValue = $fooValue - $cowValue;
if($diffValue <= 0.01) {
    echo("success");
} else {
    echo("error");
}

This will show "error".

I know what to do in Java. But I'm not good at PHP, especially with this calculate things.

Please help me out. I mean how to succeed this?

回答1:

Float is an inexact datatype (as all floating-point datatypes are), because you may lose precision when converting to and from binary. This is why you shouldn't use floating-point arithmetic when you need high (exact) precision.

In PHP, check out BC Math or the GMP library. The latter will only work with integers, but it has high performance and sometimes it's possible to convert to and from integers without losing precision.



标签: