0

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

$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。我还怀疑如果我改变计算方式(例如,最后将所有内容乘以数量),我会得到甚至不同的结果.

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

4

1 回答 1

2

我相信这就是你所需要的。请注意,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);
于 2013-12-17T14:42:06.053 回答