如何在Python3中获取十进制除法的余数?

4

我正在寻找一种用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

谢谢!
1个回答

4

将价格乘以100转换为美分,所有计算都以美分为单位,最后再转回去。

price = 10
number_of_product = 3

price_cents = price * 100

price_per_product = int(price_cents / number_of_product) / 100
# price_per_product = 3
remainder = (price_cents % number_of_product) / 100
# remainder = 1

然后使用Decimal将其转换为字符串。

重要关键词:整数! - Eric Duminil
1
我喜欢它!:) 谢谢 - Thom
不客气!多亏了你,我现在有足够的声望来发表评论了。 :D - Liam Bohl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接