Python float round error 117.285 round to 117.28 not 117.29

后端 未结 3 1683
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 17:47

I am using python 2.7, and the code I have is:

a = 10.5 * 22.34 / 2.0
print \"%.2f\" % a

and the result I expect is 117.29, but it shows 11

3条回答
  •  温柔的废话
    2020-12-10 18:43

    Mr. Skeet has the correct answer, below is an example of how to use the decimal module to which he refers:

    import decimal
    a = decimal.Decimal('117.285')
    rounded = a.quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_HALF_UP)
    print rounded
    # 117.29
    repr(rounded)
    # "Decimal('117.29')"
    

提交回复
热议问题