> Date: Mon, 18 Jul 2011 19:00:52 -0300
> From: martin.marq...@gmail.com
> To: email@example.com
> Subject: [PHP] How to sum monetary variables
> I'm building a table (which is a report that has to be printed) with a
> bunch of items (up to 300 in some cases) that have unitary price
> (stored in a numeric(9,2) field), how many there are, and the total
> price for each item. At the end of the table there is a total of all
> the items.
> The app is running on PHP and PostgreSQL is the backend.
> The question is, how do I get the total of everything?
> Running it on PHP gives one value, doing a sum() on the backend gives
> another, and I'm starting to notice that even using python as a
> calculator gives me errors (big ones). Right now I'm doing the maths
> by hand to find out who has the biggest error, or if any is 100%
> Any ideas?
According to the postgreSQL docs, there might occur an error as the sum()
output is coerced to have a 9 digit precision (so at most 9999999,99 as a
value), and as this is different from the PHP float interpretation, they might
yield different results in case of overflow. However as python supports
arbitrary integer arithmetic, overflows should not occur.
At the moment, still overflow errors seem the most likely explanation. Does
your table consist of very large values (occasionally perhaps)?
Could you give us an example?