Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to nearest 0.25 without banker's rounding in Python 3

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

like image 230
dinex Avatar asked Mar 06 '23 01:03

dinex


2 Answers

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

like image 156
John Zwinck Avatar answered Mar 16 '23 23:03

John Zwinck


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')
like image 39
user2357112 supports Monica Avatar answered Mar 16 '23 22:03

user2357112 supports Monica