PHP钱计算精度

时间:2013-10-02 03:33:23

标签: php bcmath

我有一个项目,将资金存储在数据库中的bigint列(以美分存储)。我打算改写这个东西来改用BCMATH。我不介意整数,但是它们给了我一些可怕的舍入错误事件存储在美分中我怀疑我可能在BCMATH中有相同的舍入错误。问题出现在情况中,例如在这个伪代码中:

$price = $some_price_in_cents * $store_price_increase; // second value is a float for final price calculation, so the result might have fractions of a cent
$price_total = $price * $qty;
$discount = // some discount in cents (might have fractions of a cent)
$discount *= $qty;
$discounted_price = $price_total - $discount;

当插入数据库时​​,我对所有以分为单位的值进行round()。现在我有一个记录说:

total price = 12134
discount = 460
discounted price = 11675

现在,如果我做12134 - 460 ......我显然得到11674而不是11675。 我还怀疑,如果我改变了事物的计算方式(例如,最后将数量乘以QTY),我会得到不同的结果。

我会使用BCMATH获得这种行为吗?结果会取决于数学运算的顺序吗?如何使用BCMATH正确计算上述内容并将其存储在DB中(假设需要2位小数)?

1 个答案:

答案 0 :(得分:1)

我相信这就是你所需要的。请注意,bcmath需要字符串。数字2用于指定所需的小数位数。

$price = bcmul($some_price_in_cents, $store_price_increase, 2);
$price_total = bcmul($price, $qty, 2);
$discount = bcmul($qty, "discount amount", 2);
$discounted_price = bcsub($price_total, $discount, 2);