python incorrect rounding with floating point numbers

前端 未结 4 913
再見小時候
再見小時候 2020-12-07 02:30
>>> a = 0.3135
>>> print(\"%.3f\" % a)
0.314
>>> a = 0.3125
>>> print(\"%.3f\" % a)
0.312
>>>

I am exp

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 03:16

    I had the same incorrect rounding

    round(0.573175, 5) = 0.57317

    My solution

    def to_round(val, precision=5):
        prec = 10 ** precision
        return str(round(val * prec) / prec)
    

    to_round(0.573175) = '0.57318'

提交回复
热议问题