Limiting floats to two decimal points

前端 未结 28 2877
你的背包
你的背包 2020-11-21 04:57

I want a to be rounded to 13.95.

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

The ro

相关标签:
28条回答
  • 2020-11-21 05:13

    Use combination of Decimal object and round() method.

    Python 3.7.3
    >>> from decimal import Decimal
    >>> d1 = Decimal (13.949999999999999) # define a Decimal
    >>> d1 
    Decimal('13.949999999999999289457264239899814128875732421875')
    >>> d2 = round(d1, 2) # round to 2 decimals
    >>> d2
    Decimal('13.95')
    
    0 讨论(0)
  • 2020-11-21 05:14

    With Python < 3 (e.g. 2.6 or 2.7), there are two ways to do so.

    # Option one 
    older_method_string = "%.9f" % numvar
    
    # Option two (note ':' before the '.9f')
    newer_method_string = "{:.9f}".format(numvar)
    

    But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.

    For more information on option two, I suggest this link on string formatting from the Python documentation.

    And for more information on option one, this link will suffice and has information on the various flags.

    Reference: Convert floating point number to a certain precision, and then copy to string

    0 讨论(0)
  • 2020-11-21 05:15

    The built-in round() works just fine in Python 2.7 or later.

    Example:

    >>> round(14.22222223, 2)
    14.22
    

    Check out the documentation.

    0 讨论(0)
  • 2020-11-21 05:16
    from decimal import Decimal
    
    
    def round_float(v, ndigits=2, rt_str=False):
        d = Decimal(v)
        v_str = ("{0:.%sf}" % ndigits).format(round(d, ndigits))
        if rt_str:
            return v_str
        return Decimal(v_str)
    

    Results:

    Python 3.6.1 (default, Dec 11 2018, 17:41:10)
    >>> round_float(3.1415926)
    Decimal('3.14')
    >>> round_float(3.1445926)
    Decimal('3.14')
    >>> round_float(3.1455926)
    Decimal('3.15')
    >>> round_float(3.1455926, rt_str=True)
    '3.15'
    >>> str(round_float(3.1455926))
    '3.15'
    
    0 讨论(0)
  • 2020-11-21 05:19

    The Python tutorial has an appendix called Floating Point Arithmetic: Issues and Limitations. Read it. It explains what is happening and why Python is doing its best. It has even an example that matches yours. Let me quote a bit:

    >>> 0.1
    0.10000000000000001
    

    you may be tempted to use the round() function to chop it back to the single digit you expect. But that makes no difference:

    >>> round(0.1, 1)
    0.10000000000000001
    

    The problem is that the binary floating-point value stored for “0.1” was already the best possible binary approximation to 1/10, so trying to round it again can’t make it better: it was already as good as it gets.

    Another consequence is that since 0.1 is not exactly 1/10, summing ten values of 0.1 may not yield exactly 1.0, either:

    >>> sum = 0.0
    >>> for i in range(10):
    ...     sum += 0.1
    ...
    >>> sum
    0.99999999999999989
    

    One alternative and solution to your problems would be using the decimal module.

    0 讨论(0)
  • 2020-11-21 05:20

    You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

    With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

    Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

    For example,

    >>> 125650429603636838/(2**53)
    13.949999999999999
    
    >>> 234042163/(2**24)
    13.949999988079071
    
    >>> a = 13.946
    >>> print(a)
    13.946
    >>> print("%.2f" % a)
    13.95
    >>> round(a,2)
    13.949999999999999
    >>> print("%.2f" % round(a, 2))
    13.95
    >>> print("{:.2f}".format(a))
    13.95
    >>> print("{:.2f}".format(round(a, 2)))
    13.95
    >>> print("{:.15f}".format(round(a, 2)))
    13.949999999999999
    

    If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

    1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
    2. Or use a fixed point number like decimal.
    0 讨论(0)
提交回复
热议问题