views:

162

answers:

5

I want to compare two floats in php, below is a sample code

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

In this code it return result of else condition instead of if condition ,even $a and $ b are same. Is there any special way to handle/compare float in php.

If yes then please help me to solve this issue.

Or there is problem with my server config.

+7  A: 

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) < 0.00001) {
  echo "same";
}

Something like that.

Joey
golden answer for these questions (thousands of them).
Andrey
Thanks Johannes, it worked for me . .. thanks a lot.
santosh
A: 

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/

Adam Wright
A: 
function floatcmp($f1,$f2,$precision = 10)
{
    $e = pow(10,$precision);
    return (intval($f1 * $e) == intval($f2 * $e));
}

Test Case

$a = 0.17;
$b = 0.17;

echo floatcmp($a,$b) ? 'yes' : 'no'; // yes
echo floatcmp($a,$b + 0.01) ? 'yes' : 'no'; // no
RobertPitt
it is not performance efficient.
Andrey
A: 
if( 0.1 + 0.2 == 0.3 ){
 echo 'a and b are same';
}
else {
 echo 'a and b are not same';
}

This will cause problems, because of the IEEE standard floating point arithmetic (which has this problem).

galambalazs
Every fixed-precision floating-point arithmetic has this problem; that's not a unique trait of IEEE 754
Joey
+5  A: 

read the red warning first http://www.php.net/manual/en/language.types.float.php you must never compare floats for equality. use epsilon technique. consider numbers equal

if (abs($a-$b) < EPSILON) { … }

where EPSILON is constant representing very small number. (you define it)

Andrey