我可能遗漏了一些重要的东西,但我无法找到一种方法来在Python(2.7)中将浮点/小数“适当”舍入,至少舍入到小数点后三位。我的意思是1.2225应该四舍五入到1.223,而1.2224应该四舍五入到1.222。在
我知道在Python中,round不适用于float,但我似乎无法使Decimal按预期运行,也无法使ceil函数正常工作。寻找内置的功能,而不是自定义功能的解决方案,但对两者都开放。在>>> x = 1.2225 # expected: 1.223
>>> round(x, 3)
1.222 # incorrect
>>> from math import ceil
>>> ceil(x * 1000.0) / 1000.0
1.223 # correct
>>> y = 1.2224 # expected: 1.222
>>> ceil(y * 1000.0) / 1000.0
1.223 # incorrect
>>> from decimal import Decimal, ROUND_UP, ROUND_HALF_UP
>>> x = Decimal(1.2225)
>>> x.quantize(Decimal('0.001'), ROUND_UP)
Decimal('1.223') # correct
>>> y = Decimal(1.2224)
>>> y.quantize(Decimal('0.001'), ROUND_UP)
Decimal('1.223') # incorrect
>>> y.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222') # correct
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222') # incorrect
有没有办法得到想要的结果?在