[英]'Proper' rounding in Python, to 3 decimal places
我可能会遗漏一些必要的东西,但是我无法找到一种方法来“正确地”在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'), ROUND_HALF_UP)
Decimal('1.222') # correct
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222') # incorrect
有没有办法获得理想的结果?
问题是Decimal(1.2225)
不是你所期望的那样:
>>> Decimal(1.2225)
Decimal('1.2224999999999999200639422269887290894985198974609375')
您正在使用浮点数来创建小数,但该浮动对于您的用例来说已经太不精确了。 正如你所看到的,它实际上是1.222499
所以它小于1.2225
,因此可以正确地向下舍入。
为了解决这个问题,您需要通过将它们作为字符串传递来创建具有正确精度的小数。 一切都按预期工作:
>>> x = Decimal('1.2225')
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.223')
>>> y = Decimal('1.2224')
>>> y.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222')
这是你想要的?
float('{:,.3f}'.format(2.2225))
以下是此链接中的三个解决方案,我希望这可以帮助您准确地完成您想要做的事情。 https://gist.github.com/jackiekazil/6201722
from decimal import Decimal
# First we take a float and convert it to a decimal
x = Decimal(16.0/7)
# Then we round it to 2 places
output = round(x,2)
# Output to screen
print output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.