Python - Round to nearest 05
20,804
Solution 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)
Solution 2
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
Solution 3
Using lambda function:
>>> 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
Solution 4
Here's a one liner
def roundto(number, multiple):
return number+multiple/2 - ((number+multiple/2) % multiple)
Solution 5
There we go.
round(VALUE*2.0, 1) / 2.0
regards
Related videos on Youtube
Author by
pkdkk
Updated on September 17, 2021Comments
-
pkdkk over 2 years
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.
-
martineau over 13 yearsI'm surprised none of the answers that use the magic-number
20
bother to explain why it was chosen. -
Chris Morgan over 13 years@martineau: I'll put it here for the record in case someone can't work it out.
20 == 1 / 0.05
-
-
martineau over 13 years
decimal
is the name of a module in the python standard library, so you might want to avoid using that name. -
David Webb over 13 years
round_to_05(-1)
gives-0.95
which doesn't seem like the right result to me. -
David Webb over 13 years@martineau - You're right and it's also a bad name as the second argument doesn't have to be a decimal, you can use the function to round to whole number too, e.g.
round_to_value(36.04,5)
gives35.0
. -
martineau over 13 years+1 because this is currently the only answer that provides a generalized solution (which is, not surprisingly, generally better IMHO).
-
fortran over 13 yearstrue, I was thinking in natural numbers... I'll fix it.
-
John Machin over 13 yearsUsing "decimal" when you mean "fraction" is definitely not an aid to understanding.
-
fortran over 13 yearsthat would round to halves, you should multiply and divide by 20
-
mo-han about 3 years
correction
is not needed if we useround()
to replaceint()
like thisround(n / precision) * precision
. Then the wrapper func is not needed as well since this is really a simple line of code. However it does have some flaw, such asround(0.275/.05)*.05 == 0.30000000000000004
. To avoid that, maybe we could uselen(str(.05).split('.')[-1])
to get the number of decimal digits and useround()
again to change0.30000000000000004
to0.30
.