我试图将十进制的货币数字四舍五入到最接近的 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(可能使用量化)处理 float ?
最佳答案
对于 float ,只需使用 round(x * 2, 1)/2
。不过,这并不能控制舍入方向。
使用 Decimal.quantize
,您还可以完全控制舍入的类型和方向(Python 3.5.1):
>>> from decimal import Decimal, ROUND_UP
>>> x = Decimal("3.426")
>>> (x * 2).quantize(Decimal('.1'), rounding=ROUND_UP) / 2
Decimal('3.45')
>>> x = Decimal("3.456")
>>> (x * 2).quantize(Decimal('.1'), rounding=ROUND_UP) / 2
Decimal('3.5')
关于python - 将 python 小数舍入到最接近的 0.05,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37825909/