Limiting floats to two decimal points

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

    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
    

提交回复
热议问题