PHP float计算的准确性 [英] The accuracy of PHP float calculate

查看:95
本文介绍了PHP float计算的准确性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$fooValue = 100.68;
$cowValue = 100.67;

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

这将显示错误".

我知道用Java做些什么.但是我不擅长PHP,尤其是在计算方面.

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?

推荐答案

浮点数是不精确的数据类型(因为所有浮点数据类型都是),因为在二进制之间进行转换时可能会失去精度.这就是为什么当您需要高精度(精确)时不应该使用浮点运算的原因.

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.

在PHP中,查看 BC Math

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.

这篇关于PHP float计算的准确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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