我正在寻找一种用Python的方式来获取Decimal除法的余数。
我的用例是我想要将一个价格分配给多个产品。例如,我收到了一个10美元的订单,有3件商品,我想要在这3个产品上分配价格而不丢失任何分钱 :)
并且由于这是价格,我只想保留2位小数。
目前,我找到的解决方案如下:
from decimal import Decimal
twoplaces = Decimal('0.01')
price = Decimal('10')
number_of_product = Decimal('3')
price_per_product = price / number_of_product
# Round up the price to 2 decimals
# Here price_per_product = 3.33
price_per_product = price_per_product.quantize(twoplaces)
remainder = price - (price_per_product * number_of_product)
# remainder = 0.01
我想知道是否有更符合Python风格的方法来实现它,例如对于整数:
price = 10
number_of_product = 3
price_per_product = int(price / number_of_product)
# price_per_product = 3
remainder = price % number_of_product
# remainder = 1
谢谢!