Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

types - Best practice for working with currency values in PHP?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...