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

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


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.


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