开发者

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 t开发者_如何学编程hings 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜