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))
Answer from Alok Singhal on Stack OverflowI 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))
For rounding to non-integer values, such as 0.05:
def myround(x, prec=2, base=.05):
return round(base * round(float(x)/base),prec)
I found this useful since I could just do a search and replace in my code to change "round(" to "myround(", without having to change the parameter values.
How does the Python round function work?
How does Python round function handle 0.5 values?
What is the syntax of the Python round function?
Greetings,
Code: x = round(7.85, 2) print(x)
Result: 7.8
Why is that? Rounding down starts at 0 and ends at 4, and rounding up begins at 5 and ends at 9. The result should be 7.9.
Does Python have its own math rules? If so, why? Math is math...
Please and thank you ☺
round (0.5) = 0
round (1.5) = 2
round (2.5) = 2
round (3.5) = 4
Is it just me or does this feel like some sort of inconsistency? Why does 0.5 round to 0, when it should round to 1?
edit: it's because python uses https://en.wikipedia.org/w/index.php?title=IEEE_754#Rounding_rules
edit2: Surprised this got this much attention. Here's a code work-around someone made:
def col_round(x): frac = x - math.floor(x) if frac < 0.5: return math.floor(x) return math.ceil(x)