PHP手册里有一句话:永远不要比较两个浮点数是否相等。php
计算机内部处理浮点数的方式决定了浮点数不可能100%的精确,因此在处理浮点数运算时会出现精度损失问题。好比下面这段程序:html
[php] view plaincopyprint?优化
- <?php
- $a = 15521.42;
- $b = 15480.3;
- $c = $a-$b;
- var_dump($c); //php4:float(41.120000000001) php5:float(41.12)
- var_dump($c == 41.12); //bool(false)
- ?>
第一条输出语句:在PHP4下输出$c多是41.120000000001,或相似的结果,后面的1就属于精度损失的部分。在PHP5中对这个问题作了些“优化”,输出结果中不会显示不精确的部分,但同时也会让咱们忽视这个问题,觉得$c==41.12。spa
第二条输出语句:在PHP4和PHP5中都会输出false。.net
声明一点:这不是PHP的问题,而是计算机内部处理浮点数的问题!在C/JAVA中也会遇到一样的问题。详细的解释可参看《深刻浅出浮点数 》htm
延伸一下:咱们一样不能使用>、<、>=或<=blog
那么,咱们应该怎么比较两个浮点数相等呢?ci
看了上面的介绍后,咱们就知道了:没办法精确的比较两个浮点数相等!so..咱们只能在咱们要的精度范围内比较(好比上面的示例,咱们只须要比较$c在小数点后两位内等于41.12便可)。get
下面是PHP手册评论中的示例io
[php] view plaincopyprint?
- function floatcmp($f1,$f2,$precision = 10) {// are 2 floats equal
- $e = pow(10,$precision);
- $i1 = intval($f1 * $e);
- $i2 = intval($f2 * $e);
- return ($i1 == $i2);
- }
- function floatgtr($big,$small,$precision = 10) {// is one float bigger than another
- $e = pow(10,$precision);
- $ibig = intval($big * $e);
- $ismall = intval($small * $e);
- return ($ibig > $ismall);
- }
- function floatgtre($big,$small,$precision = 10) {// is on float bigger or equal to another
- $e = pow(10,$precision);
- $ibig = intval($big * $e);
- $ismall = intval($small * $e);
- return ($ibig >= $ismall);
- }