問題描述
我需要在 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.
一種方法是將所有內容存儲在浮點數中,在每次操作前后使用round,并在比較相等性時使用mind machine epsilon.很麻煩,恕我直言.
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.
另一種方法是以整數數據類型將整個內容存儲為美分,另外記得在我使用數據庫時來回轉換(mysql,我使用十進制數據類型).不優雅,還有很多錯誤陷阱,恕我直言.
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.
另一種方法是發明我自己的數據類型",將所有值存儲在字符串(34.12")中并創建我自己的數學替換函數.這些函數會在內部將值轉換為整數,進行計算并再次將結果輸出為字符串.令人驚訝的復雜,恕我直言.
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.
我的問題:在 PHP 中處理貨幣值的最佳實踐是什么?謝謝!
My question: what is the best practice for working with currency values in PHP? Thanks!
推薦答案
讓我自己回答這個問題.最佳實踐是創建一個金額"類.此類在內部將數量存儲為整數形式的美分,并提供 getter、setter、數學函數,如加、減和比較.干凈多了.
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.
這篇關于在 PHP 中處理貨幣值的最佳實踐?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!