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

查看:38
本文介绍了在 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.

一种方法是将所有内容存储在浮点数中,在每次操作前后使用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 中处理货币值的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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