round down to nearest number

Arnaud Delobelle arnodel at gmail.com
Fri Feb 10 04:58:35 EST 2012


On 10 February 2012 06:21, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>>>>> (3219 + 99) // 100 * 100
>> 3300
>>>>> (3289 + 99) // 100 * 100
>> 3300
>>>>> (328678 + 99) // 100 * 100
>> 328700
>>>>> (328 + 99) // 100 * 100
>> 400
>>
>> Those are all rounded up to the nearest 100 correctly.
>
> One thing to be aware of though is that while the "round down" formula
> works interchangeably for ints and floats, the "round up" formula does
> not.
>
>>>> (3300.5 + 99) // 100 * 100
> 3300.0
>

I'm surprised I haven't seen:

>>> 212 - (212 % -100)
300

Here's a function that:
* rounds up and down
* works for both integers and floats
* is only two operations (as opposed to 3 in the solutions given above)

>>> def round(n, k):
...     return n - n%k
...
>>> # Round down with a positive k:
... round(167, 100)
100
>>> round(-233, 100
... )
-300
>>> # Round up with a negative k:
... round(167, -100)
200
>>> round(-233, -100)
-200
>>> # Edge cases
... round(500, -100)
500
>>> round(500, 100)
500
>>> # Floats
... round(100.5, -100)
200.0
>>> round(199.5, 100)
100.0

-- 
Arnaud



More information about the Python-list mailing list