Rounding to the nearest 5

Tim Chase python.list at tim.thechases.com
Thu Jan 29 19:26:34 EST 2009


> 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.  3 
should round up to 5 (not down to 0) and 23.2 should round up to 
25 (not down to 20) in the same way that 8 rounds up to 10.

   tests = (
     (3, 5), # not 0
     (8, 10),
     (23.2, 25), # not 20
     (36, 35),
     (51.5, 50),
     )

   for x, expected in tests:
     result = int(round(x / 5.0) * 5)
     if result != expected:
       print "Failed:", x, result, expected
       break
   else:
     print "All tests passed"


-tkc







More information about the Python-list mailing list