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!
question from:
https://stackoverflow.com/questions/3819508/best-practice-for-working-with-currency-values-in-php 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…