用PHP处理货币(小数)是否安全? [英] Is working with money (decimal numbers) in PHP considered safe?

查看:59
本文介绍了用PHP处理货币(小数)是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL数据库中有一个个项目表,其中一个 DECIMAL(10,2)字段称为 price

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

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

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?

PHP如何掩盖这些错误?

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

推荐答案

您可以使用执行任意精度数学的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.

这篇关于用PHP处理货币(小数)是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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