-4

Why it equals allways false?

<?php

$a = (0.1+0.2);
print $a."\n";  // results in 0.3
if ( (double)$a == (double)0.3 ) {
     echo "true";
}else{
     echo "not true";
}
echo PHP_EOL;

Perl

perl -e 'if ((0.2+0.1) == 0.3) {print "true\n"; } else { print "false\n"; }'

And now in Python

python -c 'if ((0.2+0.1)!=0.3 ):  print "false" '
Fernando André
  • 1,213
  • 3
  • 19
  • 32

3 Answers3

2

You need to specify a tolerance [also referred to as epsilon] when comparing floating point values since it is not an exact representation of the number.

function f_cmp(float $a, float $b, float $tol = 0.00001) {
  if( abs($a - $b) < $tol ) { return 0; }
  else { return $a - $b; }
  // return 0 if "equal" within tolerance
  // return < 0 if $a < $b
  // return > 0 if $a > $b
  // for use with PHP functions like usort()
}

Or simply:

function f_eq(float $a, float $b, float $tol = 0.00001) {
  if( abs($a - $b) < $tol ) { return true; }
  else { return false; }
}
Sammitch
  • 30,782
  • 7
  • 50
  • 77
1

Floating point values have a limited precision. Hence a value might not have the same string representation after any processing. That also includes writing a floating point value in your script and directly printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE 754 is, read this: http://www.floating-point-gui.de/

(Standard answer for people who report such bugs at http://bugs.php.net)

bwoebi
  • 23,637
  • 5
  • 58
  • 79
1

Enter this at the Python command line:

>>> 0.2 + 0.1

You'll probably see:

0.30000000000000004

0.2 and 0.1 do not have exact representations in binary floating point. See this link for details:

http://docs.python.org/2/library/decimal.html

Daniel Bidulock
  • 2,344
  • 1
  • 26
  • 27