在PHP中使用货币值的最佳实践? [英] Best practice for working with currency values in PHP?

查看:87
本文介绍了在PHP中使用货币值的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在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.

一种方法是将所有内容存储在float中,在进行相等性比较时在每次操作前后使用回合,并注意机器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!

推荐答案

让我自己回答这个问题.最佳实践是创建金额"类.该类内部将金额存储为整数形式的美分,并提供获取器,设置器以及诸如加,减和比较之类的数学函数.干净得多.

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中使用货币值的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆