0

I've had an issue and I've googled the issue and can't find anything relevant with regards to the issue. I'm simply doing addition with two floats but they are evaluating false every time.

Down to the code:

$total = (double)$db['total'];
$postage = (double)$db['postage'];
if (($total - $postage) == 5.95){
  $abc = 1;
}elseif(($total - $postage) == 7.95){
  $abc = 2;
}elseif(($total - $postage) == 10.95){
  $abc = 3;
}else{
  $abc = 0;
}

Then the results:

echo $abc;  //outputs 0

Total and Postage types before casting to double

echo gettype($db['postage'])." ".gettype($db['total']); // Outputs: string string

Total and Postage after casting

echo gettype($postage)." ".gettype($total); // Outputs: double double

and finally the result of total - postage

echo ($total - $postage); // outputs: 7.95

I've tried with and without casting and tried the value after == in quotation marks but can't seem to find the issue at all. Could anyone point me in the right direction? It's probably something small that I'm missing here.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Liam Sorsby
  • 2,912
  • 3
  • 28
  • 51
  • 1
    Start by reading http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems then take a look at the warning on [this page](http://php.net/manual/en/language.types.float.php), the PHP Docs page also shows how to do a comparison of floats to a degree of precision – Mark Baker Sep 25 '14 at 09:23
  • @MarkBaker I was hoping it was going to be something simple or stupid that I'd missed. Thank you I'll take a look. – Liam Sorsby Sep 25 '14 at 09:24
  • 1
    Another useful reference link: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Mark Baker Sep 25 '14 at 09:41
  • @MarkBaker thank you for the reference. Apologies that it was duplicate. I've managed to resolve the issue. Thank you for your input! – Liam Sorsby Sep 25 '14 at 10:45

0 Answers0