2

Possible Duplicate:
Compare floats in php

I have the following piece of code:

$a = 1.49;
$b = 1.50;

echo $b - $a; // Outputs 0.01, which is ok

if (($b - $a) != 0.01) {
        echo "Not ok";
} else {
        echo "Ok";
}

The problem is that if statement echoes "Not ok", although the subtract result is 0.01.

Any idea why?

Community
  • 1
  • 1
Psyche
  • 8,513
  • 20
  • 70
  • 85
  • 2
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Rapptz Oct 27 '12 at 20:20
  • 2
    @Rapptz While that is generally the resource I would defer to, I'm not sure it applies here. EDIT: I am wrong. – Waleed Khan Oct 27 '12 at 20:21
  • @WaleedKhan True, floating point comparison is a tricky anyway. Not to mention this topic has been done several times over. – Rapptz Oct 27 '12 at 20:22
  • @Rapptz explain what you mean .. your reference does not offer any particular value here – Baba Oct 27 '12 at 20:23
  • I'd normally link to http://stackoverflow.com/q/588004/1331430 but this is PHP. Anyway, floating-point operations work similarly in any of these languages. – Fabrício Matté Oct 27 '12 at 20:24

2 Answers2

4

The PHP doc on floating point numbers shows how to compare them

As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations.

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

<?php
// $a and $b are equal to 5 digits of precision.
$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;

if(abs($a-$b) < $epsilon) {
    echo "true";
}
?>

Applied to your example:

$c = $b - $a;
$epsilon = 0.00001;

if (abs($a-$b-0.01) < $epsilon) {
        echo "Not ok";
} else {
        echo "Ok";
}

Outputs OK

sachleen
  • 30,730
  • 8
  • 78
  • 73
3

it's because some floating point operations. the result isn't exactly 0.01. your output is rounded by the system.

just try var_dump(($b-$a)-0.01). this should be float(8.673617379884E-18)

a solution would be if (round($b - $a,2) != 0.01)

bukart
  • 4,906
  • 2
  • 21
  • 40