使用金钱时,您通常希望尽可能晚地限制精度,以使乘法等操作不会累积舍入误差。在python 2和python 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)