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.
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.
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.
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.
The Quick Answer: Use multiple * (number / multiple) Developing a Custom Function to Round to a Multiple in Python (e.g., 2, 5, etc.)
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With