如何在python3中得到十进制除法余数?

2024-04-25 15:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在找一种Python式的方法来求十进制除法的余数。在

我在这里的用例是我想分派几个产品的一个价格。例如,我收到一份10美元的订单,其中有3件商品,我想在不损失任何一分钱的情况下发送这3件产品的价格:)

因为这是一个价格,我只想要两个小数。在

到目前为止,我找到了解决方案:

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的方法来实现它,比如integer:

^{pr2}$

谢谢你!在


Tags: of方法订单分派number产品价格product
1条回答
网友
1楼 · 发布于 2024-04-25 15:11:13

把你的价格乘以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

然后使用十进制转换为字符串。在

相关问题 更多 >

    热门问题