Alerted by a recent report about a bug in the MageBase DPS extension I went on a debugging tour. In the particular user setup the extension errorred out in this line
if ((float)$resultXml->AmountSettlement != $order->getBaseGrandTotal()) {
throw new Exception("Mismatched totals");
}
even though it shouldn’t have.
Sending both values to the Magento log directly before this line revealed the following:
(float)$resultXml->AmountSettlement = 13;
$order->getBaseGrandTotal() = 13;
Clearly something is going on since to the untrained eye 13 = 13 seems like the same amounts.
Thinking that maybe the comparison also takes type into consideration we tried by adding an additional (float) cast in there, $order->getBaseGrandTotal() is after all saved in the database as a mysql decimal field “13.0000″
if ((float)$resultXml->AmountSettlement != (float)$order->getBaseGrandTotal()) {
throw new Exception("Mismatched totals");
}
Unfortunately the outcome was the same.
The solution we have come up with is to make the comparison a bit softer:
if (abs((float)$resultXml->AmountSettlement - $order->getBaseGrandTotal() >0.0005)) {
If the two absolute values of the two amounts are within 5% of a cent it is good enough for me.
Have you come across a similar behaviour with php before? Any other explanations you know of?
ps: The change will be uploaded to Magento Connect with the next version.
Originally published on magebase.com. Copyright © 2010 Magebase - All Rights Reserved.




Proud members of the 









I’ve had the same problem. Apparently, floats are not completely precise.
http://www.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.”
Hi Anders,
thanks for the link – that explains the issue perfectly. Php should really throw a warning or notice whenever doing a comparison including a float if this is such a known issue.