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
Simply multiply by 4, round, then divide by 4.
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')
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