21

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

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Daniyal
  • 885
  • 3
  • 16
  • 28

4 Answers4

35

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
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • a beautiful generic solution. How can I mark all the given solutions as 'accepted answer' ? – Daniyal Nov 14 '11 at 08:23
  • 4
    @Daniyal: you can't. My usual behaviour, if the answers _can't_ be sorted on merit, is to give it (along with an upvote) to the guy with the lowest rep and also upvote the others. In this case, that's not me unfortunately :-) – paxdiablo Nov 14 '11 at 08:43
32
>>> 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
>>> 
rytis
  • 2,649
  • 22
  • 27
4

There is no builtin, but such a function is trivial to write

def roundQuarter(x):
    return round(x * 4) / 4.0
6502
  • 112,025
  • 15
  • 165
  • 265
3

The solution of paxdiablo can be a little bit improved.

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

so the function is now: "data-type sensitive".

user26316
  • 39
  • 2