Python - Round to nearest 05

后端 未结 9 1863
死守一世寂寞
死守一世寂寞 2020-11-29 08:14

Hvor can I en python do the following rounding:

Round to the nearest 05 decimal

7,97 -> 7,95

6,72 -> 6,70

31,06 -> 31,05

36,04 -> 36,

相关标签:
9条回答
  • 2020-11-29 09:16

    Using lambda function:

    >>> nearest_half = lambda x: round(x * 2) / 2
    >>> nearest_half(5.2)
    5.0
    >>> nearest_half(5.25)
    5.5
    >>> nearest_half(5.26)
    5.5
    >>> nearest_half(5.5)
    5.5
    >>> nearest_half(5.75)
    6.0
    
    0 讨论(0)
  • 2020-11-29 09:21

    To round it to exactly how you want to:

    >>> def foo(x, base=0.05):
    ...     return round(base*round(x/base), 2)
    
    >>> foo(5.75)
    5.75
    >>> foo(5.775)
    5.8
    >>> foo(5.77)
    5.75
    >>> foo(7.97)
    7.95
    >>> foo(6.72)
    6.7
    >>> foo(31.06)
    31.05
    >>> foo(36.04)
    36.05
    >>> foo(5.25)
    5.25
    
    0 讨论(0)
  • 2020-11-29 09:21
    import numpy as np
    

    for Roundup

    df['a']=(df["a"]*2).apply(np.ceil)/2
    

    for Round

    df['a']=(df["a"]*2).apply(np.floor)/2
    

    This is working with columns for roundup 0.5 using numpy...

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