Python - 舍入到最接近的05

时间:2010-11-24 10:05:19

标签: python rounding

Hvor我可以让python做以下四舍五入:

舍入到最接近的05十进制

7,97 - > 7,95

6,72 - > 6,70

31,06 - > 31,05

36,04 - > 36,05

5,25 - > 5,25

希望它有意义。

9 个答案:

答案 0 :(得分:26)

def round_to(n, precision):
    correction = 0.5 if n >= 0 else -0.5
    return int( n/precision+correction ) * precision

def round_to_05(n):
    return round_to(n, 0.05)

答案 1 :(得分:12)

def round05(number):
    return (round(number * 20) / 20)

或者更一般地说:

def round_to_value(number,roundto):
    return (round(number / roundto) * roundto)

唯一的问题是because you're using floats you won't get exactly the answers you want

>>> round_to_value(36.04,0.05)
36.050000000000004

答案 2 :(得分:3)

我们走了。

round(VALUE*2.0, 1) / 2.0

问候

答案 3 :(得分:3)

使用lambda函数:

>>> 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

答案 4 :(得分:2)

这是一个单线

def roundto(number, multiple):
   return number+multiple/2 - ((number+multiple/2) % multiple)

答案 5 :(得分:1)

将其四舍五入到您想要的方式:

>>> 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

答案 6 :(得分:0)

我遇到了同样的问题,由于找不到此解决方案的最终解决方案,这是我的。

所有主要部分的内容(之前已回答):

def find_first_meaningful_decimal(x):
    candidate = 0
    MAX_DECIMAL = 10
    EPSILON = 1 / 10 ** MAX_DECIMAL
    while round(x, candidate) < EPSILON:
        candidate +=1
        if candidate > MAX_DECIMAL:
            raise Exception('Number is too small: {}'.format(x))
    if int(x * 10 ** (candidate + 1)) == 5:
        candidate += 1
    return candidate


print(round_to_precision(129.950002, 0.0005))
print(round_to_precision(-129.95005, 0.0001))

129.9505
-129.9501

这里唯一棘手的部分是 find_first_有意义_十进制,我已经这样实现了:

{{1}}

答案 7 :(得分:0)

import numpy as np

针对综述

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

回合

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

这适用于使用numpy进行舍入0.5的列...

答案 8 :(得分:-1)

接受答案的延伸。

def round_to(n, precision):
    correction = precision if n >= 0 else -precision
    return round(int(n/precision+correction)*precision, len(str(precision).split('.')[1]))


test_cases = [101.001, 101.002, 101.003, 101.004, 101.005, 101.006, 101.007, 101.008, 101.009]
[round_to(-x, 0.003) for x in test_cases]
[-101.001, -101.001, -101.001, -101.004, -101.004, -101.004, -101.007, -101.007, -101.007]