Rounding to the nearest 5

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Jan 29 22:51:16 EST 2009


On Thu, 29 Jan 2009 18:26:34 -0600, Tim Chase wrote:

>> How can you make python round numbers to the nearest 5:
>>  
>> Example:
>>  
>> 3 => 0
>> 8 => 10
>> 23.2 => 20
>> 36 => 35
>> 51.5 => 50
> 
> I'm not sure *any* rounding system will give those results.

Round towards zero.


> 3 should round up to 5 (not down to 0) 

That would be round to nearest.



>      result = int(round(x / 5.0) * 5)

I think that should work. It even works for negative values:


>>> int(round(-2.2 / 5.0) * 5)
0
>>> int(round(-2.7 / 5.0) * 5)
-5




-- 
Steven



More information about the Python-list mailing list