round() function strange behaviour

Tim Peters tim.one at comcast.net
Sun Mar 10 13:31:38 EST 2002


[brobbins333 at shaw.ca]
> OK, that makes perfect sense. In my case, I was simply looking for a
> predictable way to return a number with two decimal places -- knowing
> that it will be an approximation of Python's approximation. Obviously,
> using round() is not the way to go about this. I'll figure it out.

round() is the best way to go about this, provided you're going to stick
with using Python floats.  Grant Edwards explained why:  most decimal
numbers aren't exactly representable as floats, and round(x, 2) generally
delivers a float y such that y is approximately equal to x and such that
y*100 is as close to being an exact integer as is (even theoretically)
possible.

If you want exact decimal numbers, you can't use floats at all.  In a
parallel thread, Aahz announced that he put up my old FixedPoint class
(thanks, Aahz!):

     http://starship.python.net/crew/aahz/FixedPoint.py

That simulates exact decimal arithmetic.

at-high-cost-but-so-it-goes-ly y'rs  - tim





More information about the Python-list mailing list