在MySQL和PHP中处理货币时如何处理精度

时间:2016-04-21 21:38:47

标签: php mysql rounding currency-formatting

发票表中有三个字段:

subtotal    decimal(12,4)
tax_amount  decimal(12,4)
total       decimal(12,4)

我遇到了四舍五入的问题。因此,发票上面有以下值。添加会增加,但在显示发票数据并生成发票的pdf时,显示的数据并不总是相加。

           stored value     displayed (rounded)
                                value
subtotal    165.1610         165.16 
tax_amount  24.7742          24.77
total       189.9352         189.94

存储的值加起来。通过在PHP中添加totalsubtotal值来计算tax_amount列。舍入是正确的,但165.16 + 24.77 = 189.93 而不是189.94。

我该如何处理这些情况?情况并非总是如此。

1 个答案:

答案 0 :(得分:2)

Round the stored values to the nearest penny. When you're calculating a total or subtotal using PHP, sum up the rounded values.

If you're going to be displaying rounded aggregates a certain way, it's probably best practice to calculate it the exact same way to avoid confusion.

You could display the aggregate items as not being rounded, and then round the final sum for display purposes. This may play more nicely in the long run if you're storing fractional pennies in the database.

Another option could be having a rounding charge on the invoice to account for the discrepancy, though that may confuse some people.

That being said, programmatically speaking, it's best to avoid fractional pennies whenever possible.

Whatever you choose to do, be consistent!