如何在python3中获取小数除法余数?

汤姆

我在寻找一种Python方式来获取Decimal除法的余数。

我在这里的用例是我想为多个产品分配一个价格。例如,我收到一个包含3件商品的10美元订单,我想在不损失任何美分的情况下分摊这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

我想知道是否还有一种更pythonic的方式来做到这一点,例如对于整数:

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

谢谢 !

利亚姆·波尔(Liam Bohl)

通过将价格乘以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转换为字符串。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章