Round up to Second Decimal Place in Python

后端 未结 11 1251
耶瑟儿~
耶瑟儿~ 2020-11-30 07:16

How can I round up a number to the second decimal place in python? For example:

0.022499999999999999

Should round up to 0.03<

11条回答
  •  悲&欢浪女
    2020-11-30 07:52

    Here's a simple way to do it that I don't see in the other answers.

    To round up to the second decimal place:

    >>> n = 0.022499999999999999
    >>> 
    >>> -(-n//.01) * .01
    0.03
    >>> 
    

    Other value:

    >>> n = 0.1111111111111000
    >>> 
    >>> -(-n//.01) * .01
    0.12
    >>> 
    

    With floats there's the occasional value with some minute imprecision, which can be corrected for if you're displaying the values for instance:

    >>> n = 10.1111111111111000
    >>> 
    >>> -(-n//0.01) * 0.01
    10.120000000000001
    >>> 
    >>> f"{-(-n//0.01) * 0.01:.2f}"
    '10.12'
    >>> 
    

    A simple roundup function with a parameter to specify precision:

    >>> roundup = lambda n, p: -(-n//10**-p) * 10**-p
    >>> 
    >>> # Or if you want to ensure truncation using the f-string method:
    >>> roundup = lambda n, p: float(f"{-(-n//10**-p) * 10**-p:.{p}f}")
    >>> 
    >>> roundup(0.111111111, 2)
    0.12
    >>> roundup(0.111111111, 3)
    0.112
    

提交回复
热议问题