Limiting floats to two decimal points

前端 未结 28 2875
你的背包
你的背包 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:10

    Nobody here seems to have mentioned it yet, so let me give an example in Python 3.6's f-string/template-string format, which I think is beautifully neat:

    >>> f'{a:.2f}'
    

    It works well with longer examples too, with operators and not needing parens:

    >>> print(f'Completed in {time.time() - start:.2f}s')
    
    0 讨论(0)
  • 2020-11-21 05:10

    To round a number to a resolution, the best way is the following one, which can work with any resolution (0.01 for two decimals or even other steps):

    >>> import numpy as np
    >>> value = 13.949999999999999
    >>> resolution = 0.01
    >>> newValue = int(np.round(value/resolution))*resolution
    >>> print newValue
    13.95
    
    >>> resolution = 0.5
    >>> newValue = int(np.round(value/resolution))*resolution
    >>> print newValue
    14.0
    
    0 讨论(0)
  • 2020-11-21 05:11

    What about a lambda function like this:

    arred = lambda x,n : x*(10**n)//1/(10**n)
    

    This way you could just do:

    arred(3.141591657,2)
    

    and get

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

    lambda x,n:int(x*10n+.5)/10n has worked for me for many years in many languages.

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

    I feel that the simplest approach is to use the format() function.

    For example:

    a = 13.949999999999999
    format(a, '.2f')
    
    13.95
    

    This produces a float number as a string rounded to two decimal points.

    0 讨论(0)
  • 2020-11-21 05:12
    orig_float = 232569 / 16000.0
    

    14.5355625

    short_float = float("{:.2f}".format(orig_float)) 
    

    14.54

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