Python - до ближайшего 05 - PullRequest
       7

Python - до ближайшего 05

13 голосов
/ 24 ноября 2010

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

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

7,97 -> 7,95

6,72 -> 6,70

31,06 -> 31,05

36,04 -> 36,05

5,25 -> 5,25

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

Ответы [ 7 ]

26 голосов
/ 24 ноября 2010
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)
12 голосов
/ 24 ноября 2010
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
3 голосов
/ 06 сентября 2017

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

>>> 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
3 голосов
/ 24 ноября 2010

Вот и мы.

round(VALUE*2.0, 1) / 2.0

привет

2 голосов
/ 21 декабря 2013

Вот один лайнер

def roundto(number, multiple):
   return number+multiple/2 - ((number+multiple/2) % multiple)
1 голос
/ 28 июня 2015

Чтобы округлить его точно так, как вы хотите:

>>> 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 голосов
/ 01 сентября 2014

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

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