Ответ 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)
Hvor может ли я использовать python для следующего округления:
От округления до ближайшего 05 десятичного числа
7,97 → 7,95
6,72 → 6,70
31,06 → 31,05
36,04 → 36,05
5,25 → 5,25
Надеюсь, что это имеет смысл.
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)
def round05(number):
return (round(number * 20) / 20)
Или более общее:
def round_to_value(number,roundto):
return (round(number / roundto) * roundto)
Единственная проблема потому что вы используете поплавки, вы не получите именно те ответы, которые вы хотите:
>>> round_to_value(36.04,0.05)
36.050000000000004
Мы идем.
round(VALUE*2.0, 1) / 2.0
рассматривает
Здесь один вкладыш
def roundto(number, multiple):
return number+multiple/2 - ((number+multiple/2) % multiple)
Чтобы объединить его так, как вы хотите:
>>> 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
Использование лямбда-функции:
>>> 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
Расширение принятого ответа.
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]