标签:
在Python中,round函数对小数进行四舍五入的截断。
然而:
>>> round(3.55, 1) 3.5
官方文档对于函数的解释是:
Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.
>>> round(0.55, 1) 0.6 >>> round(3.55, 1) 3.5
>>> from decimal import Decimal >>> Decimal(0.55) Decimal(‘0.5500000000000000444089209850062616169452667236328125‘) >>> Decimal(3.55) Decimal(‘3.54999999999999982236431605997495353221893310546875‘)
一种正确四舍五入的解决方案是用decimal模块实现:
from decimal import * number = ‘17.9555‘ print Context(prec = len(number.split(‘.‘)[0]) + 3, rounding = ROUND_HALF_UP).create_decimal(number)
代码里加粗部分的解释:
标签:
原文地址:http://www.cnblogs.com/ijkcherry/p/4567876.html