Is round() broken?

Thomas Jensen thomasNO at SPAM.obscure.dk
Wed Oct 31 17:27:08 EST 2001


"Joseph Wilhelm" <jwilhelm at outsourcefinancial.com> wrote in
news:mailman.1004561433.28620.python-list at python.org: 

> Hello again everybody!
> 
> I'm having some troubles with round() now... either I'm doing it
> completely wrong or round() is.  But here's what I'm getting.
> 
>>>> round( 43583.010000000002, 2 ) 43583.010000000002 round(
>>>> 43583.010000000002 ) 43583.0 round( 43583.010000000002, 1 )
>>>> 43583.0 round( 43583.010000000002, 2 ) 43583.010000000002 
>>>>
> 
> So, what this is saying.. is that rounding to 1 decimal point
> works... but anything beyond that is broken?  Rounding negative
> will round the number before the decimal point also.

You're probably seeing this, because the number cannot be represented 
precisely as a float. This is the nature of floating point numbers, the 
way they are represented by most (all?) CPUs today, and thus not a 
problem specific to Python. the number 1.1 is another example of this.
If you want to get a string representation of the number with only 2 
digits, try '%.2f' % number.
http://www.python.org/doc/current/lib/typesseq-strings.html

A python session:
>>> round( 43583.010000000002, 2 )
43583.010000000002
>>> '%.2f' % 43583.010000000002
'43583.01'
>>> eval('%.2f' % 43583.010000000002)
43583.010000000002
>>> 43583.01
43583.010000000002
>>> 1.1
1.1000000000000001

> And actually, as a side question.. that number was pulled from a
> float8 field in a Postgres database, using the 'pg' module. If I
> look at the field through pgAdmin, I just see it as "43583.01",
> instead of that whole big long decimal. Is it supposed to come out
> like this? 

Perhaps the float8 datatype is stored differently than python floats ?

-- 
Best Regards
Thomas Jensen



More information about the Python-list mailing list