0

I have an ojbect $order that has a member function amount() that adds up the sum of the line items (all floats) then returns the value (again, as a float).

var_dump(array(
    $order->amount() * 100.0, 
    intval($order->amount() * 100.0),
));

result:

Array
(
    [0] => 7500
    [1] => 7499
)

The values of the line items are all under 1000 and never have more than 2 decimal points...

What is the best way to deal with decimal values in PHP, since the lack of precision is causing problems for me...

EDIT: To better illustrate:

echo "Addition: " . intval((172.45 - 72.45 - 25.0) * 100);

Result:

Addition: 7499
Ian
  • 24,116
  • 22
  • 58
  • 96
  • As stated above, everything is a float, no strings, no ints (except for that intval() ) – Ian May 01 '12 at 02:54
  • 2
    This is why we don't use floats in finance. – Ignacio Vazquez-Abrams May 01 '12 at 03:01
  • There seems to be plenty of discussion on this topic if you search around. http://stackoverflow.com/questions/4662138/if-dealing-with-money-in-a-float-is-bad-then-why-does-money-format-do-it OR http://stackoverflow.com/questions/1081988/php-mysql-best-money-operations-storing-practices – PorridgeBear May 01 '12 at 03:04
  • What's the alternative in PHP? There is no decimal type in PHP that keeps its precision... – Ian May 01 '12 at 03:04
  • 2
    @ian: do everything in cents instead of dollars. That eliminates having to drag around 2 decimal places. – Marc B May 01 '12 at 04:00
  • I guess I'll have to do that, but this still leaves the problem of applying taxes, since I'll be multiplying against floats... The solution I've opted for right now is to round($var, 2) after every arithmetic operation. Since I never use large numbers or very small numbers, this shouldn't be a problem. – Ian May 01 '12 at 13:19

0 Answers0