is int(round(val)) safe?

Dan Bishop danb_83 at yahoo.com
Tue Nov 23 08:00:55 EST 2004


"Russell E. Owen" <rowen at cesmail.net> wrote in message news:<rowen-8AF206.11131622112004 at gnus01.u.washington.edu>...
> I realize this probably a stupid question, but...is it safe to 
> round to the nearest integer by using int(round(val))?
> 
> I suspect it is fine, but wanted to be sure that weird floating point 
> representation on some platform might make it unsafe there (i.e. get the 
> wrong value due to the floating point value being an approximation) and 
> if so, is there a Better Way).

Yes, int(round(val)) is safe.  The only concern is avoiding errors in
"val" itself.  For example,

>>> val
3.4999999999999996      # Should have been exactly 3.5
>>> int(round(val))
3                       # Should have been 4



More information about the Python-list mailing list