Best practice for working with currency values in PHP? Best practice for working with currency values in PHP? php php

Best practice for working with currency values in PHP?


As of MySQL v5.0.3, MySQLs DECIMAL datatype stores an exact decimal number, i.e. not an inaccurate floating point representation.

To correctly manipulate precision numbers in PHP use the arbitrary precision math functions. Internally this library manipulates text strings.

Currency is intended to be stored as a decimal number, you can get units of money smaller than cents. You should only round any values when displaying the figures, not during manipulation or storage.


Update 2016:

A couple of years later and hopefully a little bit wiser ;)
Since this answer still receives the occasional up- and down vote I felt the need to revise my answer. I absolutely do not advise storing 'money' as integers anymore. The only true answer is Andrew Dunn's: Use Mysql's DECIMAL type and encapsulate php's bc_* functions in a Currency class.


I will keep my outdated answer here for completeness sake

You should always work with integers. Store the values as ints in your database, use ints to do calculations and when, and only when, you want to print it, convert it to some readable format.

This way you completeley circumvent floating point problems, which, generally, is a big problem when working with money ;)

Edit: One thing worth mentioning: You need to think about precision before you start working this way. As others have pointed out, you might need to work with values smaller than a cent, so you need to do your multiplication/division accordingly. (ie currency * 1000 for a .001 precision)


Let me answer this myself. Best practice would be to create a "money amount" class. This class stores the amount internally as cents in integers, and offers getters, setters, math functions like add, subtract and compare. Much cleaner.