Python:如何管理float和int之间的舍入行为?

时间:2013-08-23 14:16:33

标签: python floating-point integer rounding

在执行操作时避免舍入问题的最佳方法是什么:

>>> a =8.92138 
>>> a
8.92138 
>>> int(a*100000)
892137

十进制给了我

>>> Decimal(a)
Decimal('8.921379999999999199644662439823150634765625')

2 个答案:

答案 0 :(得分:4)

int不会舍入 - 它找到了底线(截断小数部分)。

>>> n = 8.92138
>>> '%.42f' % n   # what n really is
'8.921379999999999199644662439823150634765625'
>>> 100000 * n # result is slightly lower than 892138
892137.9999999999
>>> int(100000 * n) # int takes the floor
892137

答案 1 :(得分:2)

如果可能,请从头开始使用十进制:

>>> a = Decimal('8.92138')
>>> int(a * 100000)
892138

要使用Decimal.quantize

>>> a = 8.92138
>>> Decimal(a) * 100000
Decimal('892137.9999999999199644662440')
>>> (Decimal(a) * 100000).quantize(1)
Decimal('892138')

>>> str(a)
'8.92138'
>>> int(Decimal(str(a)) * 100000)
892138