Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Rounding by quarter-intervals

I'm running into the following issue:

Given various numbers like:

10.38

11.12

5.24

9.76

does an already 'built-in' function exists to round them up to the closest 0.25 step like e.g.:

10.38 --> 10.50

11.12 --> 11.00

5.24 --> 5.25

9.76 --> 9-75 ?

Or can I go ahead and hack together a function that performs the desired task?

Thanks in advance and

with best regards

Dan

like image 713
Daniyal Avatar asked Nov 14 '11 07:11

Daniyal


People also ask

How do you round to the nearest .25 in Python?

If you want to round up, use math. ceil . @Thom "round" means go to the nearest. Use floor or ceil to go down or up always.

Does Python round 0.5 up or down?

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.

What is round 0.5 in Python?

Values are rounded to the closest multiple of 10 to the power minus decimalplaces; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).


2 Answers

This is a general purpose solution which allows rounding to arbitrary resolutions. For your specific case, you just need to provide 0.25 as the resolution but other values are possible, as shown in the test cases.

def roundPartial (value, resolution):
    return round (value / resolution) * resolution

print "Rounding to quarters"
print roundPartial (10.38, 0.25)
print roundPartial (11.12, 0.25)
print roundPartial (5.24, 0.25)
print roundPartial (9.76, 0.25)

print "Rounding to tenths"
print roundPartial (9.74, 0.1)
print roundPartial (9.75, 0.1)
print roundPartial (9.76, 0.1)

print "Rounding to hundreds"
print roundPartial (987654321, 100)

This outputs:

Rounding to quarters
10.5
11.0
5.25
9.75
Rounding to tenths
9.7
9.8
9.8
Rounding to hundreds
987654300.0
like image 58
paxdiablo Avatar answered Sep 28 '22 04:09

paxdiablo


>>> def my_round(x):
...  return round(x*4)/4
... 
>>> 
>>> assert my_round(10.38) == 10.50
>>> assert my_round(11.12) == 11.00
>>> assert my_round(5.24) == 5.25
>>> assert my_round(9.76) == 9.75
>>> 
like image 40
rytis Avatar answered Sep 28 '22 06:09

rytis