Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is working with money (decimal numbers) in PHP considered safe?

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?

like image 644
Svish Avatar asked Sep 26 '10 22:09

Svish


People also ask

Can you use decimals for money?

Dollars and cents can be expressed together as decimals. Note: In a decimal, cents are always written in double figures. Addition and subtract of money is same like addition and subtraction of decimal and whole number.

Why are decimals used in money transactions?

The advantages of DECIMAL(p,s) over INTEGER and FLOAT are that much greater precision is available (up to 32 digits as compared to 10 digits for INTEGER and 16 digits for FLOAT), and both the precision and the amount of storage required can be adjusted to suit the application.

How can decimals help you understand money?

Use Money to Introduce Decimalsa digit in one place represents ten times what it represents in the place to its right. Example: the 4 in 34 has a value of 4, the 4 in 43 has a value of 40. money & it's value. one dollar = $1.00, one dime = $0.10, one penny = $0.01.

Should you use float for money?

Floating Point Numbers & Currency Rounding Errors. A reminder to those who learned this lesson long ago, and a warning to those that have not learned it for themselves: Don't use floating point numbers for money. When doing any kind of calculation with currency, accuracy is extremely important.


2 Answers

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.

like image 189
Peter Ajtai Avatar answered Dec 07 '22 20:12

Peter Ajtai


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 :)

like image 21
alex Avatar answered Dec 07 '22 18:12

alex