0

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

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

十进制给了我

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

2 回答 2

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
于 2013-08-23T14:40:21.240 回答
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
于 2013-08-23T14:18:06.893 回答