4

I would like to round a series of number like this:

0 -> 0
0.1 -> 0
0.125 -> 0.25
0.25 -> 0.25

I have heard that I can use round(x*4)/4 to find the nearest 0.25 unit. However, there will be some problems at the boundary with this function

0.125 -> 0 (with round(x*4)/4)

Is there anyway I can do the above rounding correctly? Thanks

dinex
  • 367
  • 5
  • 15
  • 1
    @coldspeed: Those questions don't handle the rounding mode behavior the questioner is looking for (which appears to be ROUND_HALF_UP). – user2357112 Jun 10 '18 at 03:27
  • @user2357112 The question is not framed well, so I do not really want to reopen it. – cs95 Jun 10 '18 at 03:28
  • @coldspeed: Looks like it's clearer now, with the new edit. – user2357112 Jun 10 '18 at 03:42
  • [Possible duplicate](https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python) – DYZ Jun 10 '18 at 04:40

2 Answers2

4

Simply multiply by 4, round, then divide by 4.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 2
    @coldspeed: I was not aware this was a duplicate. Not everyone can be expected to search for every question every time. I do flag loads of dupes, but can't be expected to see 100% of them. It's good that you saw it. – John Zwinck Jun 10 '18 at 03:27
  • Biting the bullet, this one is on me and not a dupe in fact. Then again, advice still stands... kinda? Anyway, you may need to modify this answer to address OP's question. – cs95 Jun 10 '18 at 03:43
3

The decimal module gives more control over rounding behavior. Particularly, the ROUND_HALF_UP rounding mode rounds to the nearest option when there is a nearest option and rounds away from zero when there's a tie, matching what you want:

>>> from decimal import Decimal, ROUND_HALF_UP
>>> def round_your_way(d):
...     return (d*4).quantize(Decimal('1'), rounding=ROUND_HALF_UP)/4
...
>>> round_your_way(Decimal('0.125'))
Decimal('0.25')
>>> round_your_way(Decimal('0.1'))
Decimal('0')
>>> round_your_way(Decimal('0.25'))
Decimal('0.25')
user2357112
  • 260,549
  • 28
  • 431
  • 505