working of round()

Robert Kern robert.kern at gmail.com
Mon Apr 16 02:27:00 CEST 2007


Krishna.K.1900 at gmail.com wrote:
> Does round() always perfectly return the output expected or are there
> some artifacts which don't allow perfect functionality
> 
> Using python 2.5:
>>>> round(12.234, 2)
> 12.23
>>>> round(12.234, 3)
> 12.234
>>>> round(12.234, 1)
> 12.199999999999999
> 
> but was expecting 12.2

http://docs.python.org/tut/node16.html

> Also, for round(x,n), can't 'x' be an expression
> 
> round(5.25/2, 2)
> 
> was expecting 2.62  , but
> 
>>>> round(5.25/2, 2)
> 2.6299999999999999

round(x, n) essentially does the following:

  math.floor(x * 10**n + 0.5) / 10**n

Since (5.25/2)*100 == 262.5, adding 0.5 gives 263.0 and ultimately 2.63 as the
rounded number. round() does not do anything more complicated like round-to-even.

Use the decimal module if you want decimal arithmetic rather than binary
floating point.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list