views:

118

answers:

2

I have an items table in my MySQL database with a DECIMAL(10,2) field called price.

When fetching these values, is it safe to do calculations and such with these numbers in PHP? Or will I end up with potential rounding errors and things like that which are common when working with floating point data types?

How does PHP handle these things behind the cover? Is it safe to do money calculations with PHP?

+5  A: 

Most people measure the currency in the smallest denomination in PHP - for example, $10 AU dollars would be shown as 1000 cents.

It is then trivial to / 100 to get the dollars, and you won't get e.g. 4.9999999 values caused by floating point arithmetic.

Alternatively, you can use floating point and round to nearest minimum cent values (which may be a multiple of 5, for example).

It seems you already know about it, but for others, this is still required reading :)

alex
The correct answer and language agnostic at that
George Jempty
+2  A: 

You could make use of a PHP library that does arbitrary precision math, such as BC Math or GMP.

While making use of cents, or the smallest possible monetary unit works sometimes, what if you run into a situation where you must deal with fractions of cents? For example if you're dealing with selling and buying stocks, you must have greater precision than just cents. In situations like this, you have to make use of arbitrary precision math.

Peter Ajtai
+1 for the mention of edge cases where dealing with cents alone will not work
alex