如何使用 decimal
模块让我的小数保留在 2 位以表示金钱?
我已经设置了精度,该死的几乎所有其他东西,但都失败了。
最佳答案
在处理金钱时,您通常希望尽可能晚地限制精度,这样乘法之类的事情就不会汇总舍入误差。在 python 2 和 3 中,你可以 .quantize()
一个 Decimal
到你想要的任何精度:
unit_price = decimal.Decimal('8.0107')
quantity = decimal.Decimal('0.056')
price = unit_price * quantity
cents = decimal.Decimal('.01')
money = price.quantize(cents, decimal.ROUND_HALF_UP)
关于python - Python 3 中小数到 2 位的钱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7560455/