我在python中遇到了一个非常奇怪的问题.(使用python 2.4.x)
在Windows中:
>>> a = 2292.5
>>> print '%.0f' % a
2293
Run Code Online (Sandbox Code Playgroud)
但是在Solaris中:
>>> a = 2292.5
>>> print '%.0f' % a
2292
Run Code Online (Sandbox Code Playgroud)
但是在windows和solaris中都是一样的:
>>> a = 1.5
>>> print '%.0f' % a
2
Run Code Online (Sandbox Code Playgroud)
有人可以解释这种行为吗?我猜它的平台依赖于编译python的方式?
我可能会遗漏一些必要的东西,但是我无法找到一种方法来"正确地"在Python(2.7)中对浮点数/小数点进行舍入,至少小数点后三位.通过'正确',我的意思是1.2225应该舍入到1.223,并且1.2224应该舍入到1.222.
我知道round在设计中不能用于Python中的浮点数,但我似乎无法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'), …Run Code Online (Sandbox Code Playgroud)