[Baypiggies] rounding off problem

Ned Deily nad at acm.org
Wed Mar 23 21:48:50 CET 2011


In article 
<AANLkTikA8LxGyM8X+K6Xsk=7WvEaBBycNzyZ8KXfhAkH at mail.gmail.com>,
 Vikram K <kpguy1975 at gmail.com> wrote:

> how does one round off a float number in python? i have tried this using two
> ways but have been unsuccessful so far:
> 
> 1. IDLE 2.6.6      ==== No Subprocess ====
> >>> x = 3.5666666
> >>> x = round(x,3)
> >>> x
> 3.5670000000000002

I don't think anyone has mentioned that this behavior was changed as of 
Python 2.7 and 3.1.

"The repr() of a float x is shorter in many cases: it¹s now based on the 
shortest decimal string that¹s guaranteed to round back to x. As in 
previous versions of Python, it¹s guaranteed that float(repr(x)) 
recovers x."

http://docs.python.org/whatsnew/2.7.html#python-3-1-features

$ python2.5 -c 'print(repr(round(3.5666666,3)))'
3.5670000000000002
$ python2.6 -c 'print(repr(round(3.5666666,3)))'
3.5670000000000002
$ python2.7 -c 'print(repr(round(3.5666666,3)))'
3.567
$ python3.1 -c 'print(repr(round(3.5666666,3)))'
3.567
$ python3.2 -c 'print(repr(round(3.5666666,3)))'
3.567

-- 
 Ned Deily,
 nad at acm.org



More information about the Baypiggies mailing list