1

the summary here:

$a = 213480.7-190.46;
exit($a-213290.24);
# 2.9103830456734E-11

the result output suppose to be 0. but it output

the story of the operation result :

$b is : 213480.7
-190.46
$b is : 213290.24

now the balance looks correct. but when use comparison operator.. the result is weird here is the var_dump and compare result

var_dump($b);
# float 213290.24

if ($b==213290.24) {
    exit('same');
} elseif ($b>213290.24) {
    exit('larger '.($b-213290.24));
} else {
    exit('smaller '.($b-213290.24));
}
#larger 2.9103830456734E-11

can anyone tell me how to solve it??

5
  • vote down? i dont understand? is my problem?? Commented Nov 15, 2011 at 6:03
  • I didn't downvote, but you already tagged your question with the answer: floating-accuracy. Commented Nov 15, 2011 at 6:05
  • thanks for identify the problem for me. no solution? Commented Nov 15, 2011 at 6:07
  • 1
    That depends on what your goal is with this. Allowing some diversion is the usual thing to do (abs(123.456 - $a) < 0.002), but it may not be what you want. Commented Nov 15, 2011 at 6:08
  • ok. then i'll try alternative solution. thanks. Commented Nov 15, 2011 at 6:13

3 Answers 3

2

See here: http://php.net/manual/en/language.types.float.php

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

The common method of dealing with float comparisons is to add an allowable epsilon, or small difference in floating point values, so anything within a small tolerance is considered equivalent.

if (abs(213290.24 - $b) < .001) {
    exit('same')
}
Sign up to request clarification or add additional context in comments.

Comments

2

Computations performed on floating point numeric values always have inherent error resulting from their machine representation. For this reason, you should not use the equality operator == to compare floating point values.

The typical approach is to decide on a minimum allowable error, and check if the difference between the values you want to compare is less than the desired error.

$min_error = 0.00001;
if (abs($a - $b) < $min_error) 
{
   exit("same");
}

Comments

0

This is not problem of php, it's connected with the nature of binary float. You can't represent all rational number accurately with float. For example, you might try to compare 0.1 + 0.2 == 0.3, it will be failse, because 0.3 is not represented accurately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.