Подтвердить что ты не робот

Python - от раунда до ближайшего 05

Hvor может ли я использовать python для следующего округления:

От округления до ближайшего 05 десятичного числа

7,97 → 7,95

6,72 → 6,70

31,06 → 31,05

36,04 → 36,05

5,25 → 5,25

Надеюсь, что это имеет смысл.

4b9b3361

Ответ 1

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)

Ответ 3

Мы идем.

round(VALUE*2.0, 1) / 2.0

рассматривает

Ответ 4

Здесь один вкладыш

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

Ответ 5

Чтобы объединить его так, как вы хотите:

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

Использование лямбда-функции:

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

Ответ 7

Расширение принятого ответа.

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]