在 PHP 中使用金钱(十进制数字)被认为是安全的吗?

发布于 2024-09-24 20:36:28 字数 225 浏览 2 评论 0原文

我的 MySQL 数据库中有一个 items 表,其中有一个名为 priceDECIMAL(10,2) 字段。

当获取这些值时,在 PHP 中使用这些数字进行计算等是否安全?或者我最终会遇到潜在的舍入错误以及类似在使用浮点数据类型时常见的问题吗?

PHP 是如何在幕后处理这些事情的?使用 PHP 进行金钱计算安全吗?

I have an items table in my MySQL database with a DECIMAL(10,2) field called price.

When fetching these values, is it safe to do calculations and such with these numbers in PHP? Or will I end up with potential rounding errors and things like that which are common when working with floating point data types?

How does PHP handle these things behind the cover? Is it safe to do money calculations with PHP?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

饮惑 2024-10-01 20:36:28

您可以使用执行任意精度数学的 PHP 库,例如 BC Math GMP

虽然有时使用美分或尽可能小的货币单位是有效的,但如果您遇到必须处理美分的分数的情况该怎么办?例如,如果您正在处理股票的买卖,则必须具有比仅美分更高的精度。在这种情况下,您必须使用任意精度的数学。

You could make use of a PHP library that does arbitrary precision math, such as BC Math or GMP.

While making use of cents, or the smallest possible monetary unit works sometimes, what if you run into a situation where you must deal with fractions of cents? For example if you're dealing with selling and buying stocks, you must have greater precision than just cents. In situations like this, you have to make use of arbitrary precision math.

迷鸟归林 2024-10-01 20:36:28

大多数人以 PHP 的最小面额来衡量货币 - 例如,10 澳元将显示为 1000 美分。

然后,/ 100 即可轻松获得美元,并且您不会获得由浮点运算引起的例如 4.9999999 值。

或者,您可以使用浮点并舍入到最接近的最小分值(例如,可能是 5 的倍数)。

看来已经知道了,但对于其他人来说,这仍然是必读:)

Most people measure the currency in the smallest denomination in PHP - for example, $10 AU dollars would be shown as 1000 cents.

It is then trivial to / 100 to get the dollars, and you won't get e.g. 4.9999999 values caused by floating point arithmetic.

Alternatively, you can use floating point and round to nearest minimum cent values (which may be a multiple of 5, for example).

It seems you already know about it, but for others, this is still required reading :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文