php - How to transform the Magento order price in cents? -
i have nasty bug payments in magento
, paybox
, soap
web services, idea following:
- payment made in cents $36.37 = 3637cents (
paybox
- api) what trying transform order price in cents in following way:
$cents = $order->getbasegrandtotal() * 100;
also have web service soap (strict types)
respond
$cents
amount concerts(int)
, magic happens converted amount not expected one, converted result less cent, in case3736
.$prices = array(39.8699, 12.3299, 11.3211); foreach ($prices $price) { $stuff = round($price, 2) * 100; echo $stuff . php_eol; } echo "after int conversion" . php_eol; foreach ($prices $price) { $stuff = (int) (round($price, 2) * 100); echo $stuff . php_eol; }
the result following:
3987 1233 1132 after int conversion 3986 1233 1132
question there way fix bug, seems php bug ?
your algorithm summarises this:
$price = 39.8699; // 39.869900000000001228
round($price, 2) * 100; // 3986.9999999999995453
(int)3986.9999999999995453; // 3986
you're rounding everywhere, except in last step, (int)
casting truncates. rounding more appropriate:
round($price * 100)
said that, root problem computers use binary logic , store numbers base 2, while humans use fuzzy logic , prefer base 10. there isn't problem "small" integers because there's 1 1 correspondence storing arbitrary base 10 floating points numbers in fixed-sized base 2 representation approximation. classical example 1.1 has 2 digits in base 10 periodic in base 2:
1.0001100110011001100110011001100110011001100110011001100110011001101...
that's why common advice includes using exact data types when available (decimal
in relational database, integers in client code).
Comments
Post a Comment