Rounding to the nearest 5

Tim Chase python.list at tim.thechases.com
Fri Jan 30 12:38:49 CET 2009


Steven D'Aprano wrote:
> 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.

8 => 10  ?

One can round down with

   def round_down_to_n(x, ROUNDER = 5):
     return (x // ROUNDER) * ROUNDER

but 8=>10 still fails to pass because 3 rounded down and 3+5 
rounds up.

So I call bogus data, or fall back to Miles' bogoround() function :)

-tkc







More information about the Python-list mailing list