Round to 5 (Or Other Number) in Python

Round to 5 (or other number) in Python

I don't know of a standard function in Python, but this works for me:

Python 3

def myround(x, base=5):
return base * round(x/base)

It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (round(x/5)), and then since we divided by 5, we multiply by 5 as well.

I made the function more generic by giving it a base parameter, defaulting to 5.

Python 2

In Python 2, float(x) would be needed to ensure that / does floating-point division, and a final conversion to int is needed because round() returns a floating-point value in Python 2.

def myround(x, base=5):
return int(base * round(float(x)/base))

Python function to round to the nearest .5

Python's builtin round function can be used to round a number to a certain number of decimal places. By multiplying the number by 2, rounding it to no decimal places and dividing it again, we can round a number to the nearest 0.5:

num = 3.46
result = round(num * 2) / 2
print(result) # 3.5

As a function this is:

def to_nearest_half(num):
return round(num * 2) / 2

The function can also be generalised to any decimal:

def to_nearest(num, decimal):
return round(num / decimal) * decimal

Strange behavior of round() when 5 is the digit to round

There's a possible work-around for the round function's behaviour.

import math

some_value = 35

print(math.ceil(someValue / 10) * 10 if some_value % 5 == 0 else round(some_value, -1))

This code checks if the value is divisible by 5, and if it is, it divides the value by 10, rounds UP the value (ceil), and again multiplies it by 10 - otherwise executes the simple old round function :)

You could wrap that in a function as well :-

def round_val(val):
return math.ceil(val / 10) * 10 if val % 5 == 0 else round(val, -1)

python round numbers to specific value

Mostlikely not the cleanest way to do it but :
(x + step/2)//step*step should work.

Example :
print((880+25)//50*50) returns 900.

Round to nearest 0.05 using Python

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)

round off float to nearest 0.5 in python

Try to change the parenthesis position so that the rounding happens before the division by 2

def round_off_rating(number):
"""Round a number to the closest half integer.
>>> round_off_rating(1.3)
1.5
>>> round_off_rating(2.6)
2.5
>>> round_off_rating(3.0)
3.0
>>> round_off_rating(4.1)
4.0"""

return round(number * 2) / 2

Edit: Added a doctestable docstring:

>>> import doctest
>>> doctest.testmod()
TestResults(failed=0, attempted=4)


Related Topics



Leave a reply



Submit