python incorrect rounding with floating point numbers

前端 未结 4 904
再見小時候
再見小時候 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'

    0 讨论(0)
  • 2020-12-07 03:17

    Python 3 rounds according to the IEEE 754 standard, using a round-to-even approach.

    If you want to round in a different way then simply implement it by hand:

    import math
    def my_round(n, ndigits):
        part = n * 10 ** ndigits
        delta = part - int(part)
        # always round "away from 0"
        if delta >= 0.5 or -0.5 < delta <= 0:
            part = math.ceil(part)
        else:
            part = math.floor(part)
        return part / (10 ** ndigits)
    

    Example usage:

    In [12]: my_round(0.3125, 3)
    Out[12]: 0.313
    

    Note: in python2 rounding is always away from zero, while in python3 it rounds to even. (see, for example, the difference in the documentation for the round function between 2.7 and 3.3).

    0 讨论(0)
  • 2020-12-07 03:27

    try

    print '%.3f' % round(.3125,3)
    
    0 讨论(0)
  • 2020-12-07 03:33

    If you need accuracy don't use float, use Decimal

    >>> from decimal import *
    >>> d = Decimal(0.3125)
    >>> getcontext().rounding = ROUND_UP
    >>> round(d, 3)
    Decimal('0.313')
    

    or even Fraction

    0 讨论(0)
提交回复
热议问题