Compare floats in php

2018-12-31 04:50发布

I want to compare two floats in PHP, like in this sample code:

$a = 0.17;
$b = 1 - 0.83; //0.17
if($a == $b ){
 echo 'a and b are same';
}
else {
 echo 'a and b are not same';
}

In this code it returns the result of the else condition instead of the if condition, even though $a and $b are same. Is there any special way to handle/compare floats in PHP?

If yes then please help me to solve this issue.

Or is there a problem with my server config?

19条回答
浮光初槿花落
2楼-- · 2018-12-31 05:30

If you do it like this they should be the same. But note that a characteristic of floating-point values is that calculations which seem to result in the same value do not need to actually be identical. So if $a is a literal .17 and $b arrives there through a calculation it can well be that they are different, albeit both display the same value.

Usually you never compare floating-point values for equality like this, you need to use a smallest acceptable difference:

if (abs(($a-$b)/$b) < 0.00001) {
  echo "same";
}

Something like that.

查看更多
孤独寂梦人
3楼-- · 2018-12-31 05:32

If you have a small, finite number of decimal points that will be acceptable, the following works nicely (albeit with slower performance than the epsilon solution):

$a = 0.17;
$b = 1 - 0.83; //0.17

if (number_format($a, 3) == number_format($b, 3)) {
    echo 'a and b are same';
} else {
    echo 'a and b are not same';
}
查看更多
若你有天会懂
4楼-- · 2018-12-31 05:33
//You can compare if less or more.

$parcela='250.23'; //total value
$tax = (double) '15.23'; //tax value
$taxaPercent=round((100*$tax)/$parcela,2); //tax percent 

$min=(double) '2.50';// minimum tax percent                             

if($taxaPercent < $min ){
    // tax error tax is less than 2.5
}
查看更多
泪湿衣
5楼-- · 2018-12-31 05:35

I hate to say it, but "works for me":

Beech:~ adamw$ php -v
PHP 5.3.1 (cli) (built: Feb 11 2010 02:32:22) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
Beech:~ adamw$ php -f test.php
a and b are same

Now, floating point comparisons are in general tricky - things that you might expect to be the same are not (due to rounding errors and/or representation nuances). You might want to read http://floating-point-gui.de/

查看更多
看淡一切
6楼-- · 2018-12-31 05:36

This works for me on PHP 5.3.27.

$payments_total = 123.45;
$order_total = 123.45;

if (round($payments_total, 2) != round($order_total, 2)) {
   // they don't match
}
查看更多
看淡一切
7楼-- · 2018-12-31 05:38

I ended simply with:

  uasort($_units[$k], function($a, $b)
                     {
                        $r = 0;
                        if ($a->getFloatVal() > $b->getFloatVal()) $r = 1;
                        if ($a->getFloatVal() < $b->getFloatVal()) $r = -1;
                        //print_r(["comparing {$a->getFloatVal()} vs {$b->getFloatVal()} res {$r}"]);
                        return $r * -1;
                      }
  );    
查看更多
登录 后发表回答