Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Round to nearest 05

How can I do the following rounding in python:

Round to the nearest 0.05 decimal

7,97 -> 7,95

6,72 -> 6,70

31,06 -> 31,05

36,04 -> 36,05

5,25 -> 5,25

Hope it makes sense.

like image 380
pkdkk Avatar asked Nov 24 '10 10:11

pkdkk


People also ask

Does 0.5 round up or down Python?

5 is round up for positive values and round down for negative values. For instance, both round(0.5) and round(-0.5) return 0 , while round(1.5) gives 2 and round(-1.5) gives -2 . This Python behaviour is a bit different from how rounding usually goes.

Why is .5 rounded down Python?

5 rounded down and not up if int is called, how come this is the case? This comes from the Median work where the first print produces, say a value of 5 then after being divided by 2 and calling int it becomes 2.

What is round 7.5 in Python?

Round() function in Python follows the half to even rounding strategy. In this strategy, the number is rounded off to its nearest even integer. For example, if we need to round off 7.5, it will be rounded off to its nearest even integer that is 8.

How do you round to multiples of 5 in Python?

The Quick Answer: Use multiple * (number / multiple) Developing a Custom Function to Round to a Multiple in Python (e.g., 2, 5, etc.)


2 Answers

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)
like image 58
fortran Avatar answered Oct 23 '22 18:10

fortran


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

Or more generically:

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

The only problem is because you're using floats you won't get exactly the answers you want:

>>> round_to_value(36.04,0.05)
36.050000000000004
like image 29
Dave Webb Avatar answered Oct 23 '22 19:10

Dave Webb