Best practice for working with currency values in PHP?

Viewed 22598

I need to add, multiply and compare currency values in PHP and need to be sure that it is exact down to a single cent.

One way is to store everything in float, use round before and after each operation and mind machine epsilon when comparing for equality. Quite cumbersome imho.

Another way is to store the whole thing as cents in integer data types, plus remember to convert back and forth anytime I work with the database (mysql, where I use the decimal data type). Inelegant, and many error pitfalls, imho.

Another way is to invent my own "datatype", store all values in strings ("34.12") and create my own mathematical replacement functions. These function would convert the value to integers internally, do the calculation and output the result again a strings. Suprisingly complicated, imho.

My question: what is the best practice for working with currency values in PHP? Thanks!

5 Answers

I tried multiplying the floats by 100 before all mathematical operations, then dividing by 100 before displaying the result. (It worked!)

Mathematically, that's "converting to integers" like everyone else is suggesting, but the code looks a lot more elegant without any conversion functions. Also, to avoid confusion down the line, I just added "Cents" to the end of any value names.

From the machine side, it's probably faster to use integers instead of float, but writing human-readable code I prefer my solution. (Your mileage may vary, but it worked in my application.)

Related