【发布时间】:2021-04-09 21:50:50
【问题描述】:
我正在尝试将十进制的货币数字四舍五入到最接近的 0.05。现在,我正在这样做:
def round_down(amount):
amount *= 100
amount = (amount - amount % 5) / Decimal(100)
return Decimal(amount)
def round_up(amount):
amount = int(math.ceil(float(100 * amount) / 5)) * 5 / Decimal(100)
return Decimal(amount)
有没有什么方法可以让我更优雅地做到这一点,而无需使用 python Decimals(也许使用 quantize)处理浮点数?
【问题讨论】:
-
为什么不在python中使用round?
-
@SeekAddo。我如何四舍五入到最接近的 0.05?我还需要控制舍入方向(即我需要向上/向下舍入)。
-
def round_num(amount): print(round(amount,2)) round_num(23.045954) 给你 23.05,我问一下,你希望如何向下取整像 @gurch101跨度>
-
@SeekAddo 我很确定以上两个函数可以正常工作。只是在寻找更优雅的解决方案。