Best practice for working with currency values in PHP?

Fuzz

New Member
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!
 
Back
Top