我可能遗漏了一些必要的东西,但我想不出如何在Python (2.7)中“适当地”循环浮点数/小数,至少到小数点的3位。我所说的“正确”指的是1.2225到1.223,1.2224应该是1.222。
我知道round在设计上不适用于浮点,但我似乎不能让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有没有办法得到预期的结果?
发布于 2016-12-07 15:08:43
问题是,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')发布于 2016-12-07 15:16:16
这里有三个解决方案,在这个链接,我希望这将帮助您确切的什么,你想做什么。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发布于 2016-12-07 15:07:54
这就是你要找的吗?
float('{:,.3f}'.format(2.2225))https://stackoverflow.com/questions/41020797
复制相似问题