round() function strange behaviour
Erik de Castro Lopo
nospam at mega-nerd.com
Sat Mar 9 20:29:18 EST 2002
brobbins333 at shaw.ca wrote:
>
> I knew your name was familiar! I'm reading your book right now.
> It's excellent.
Thanks :-).
> VB for one, returns a proper rounded result on these
> recalcitrant numbers.
VB probably stores rounded floating point numbers as strings instead
of the normal binary representation. VB like most scripting style
languages (ie non-stringly typed languages) often hides the
representation of the its variables.
> I'd be willing to bet that C can do it as well,
> but you should know better than I.
Python as it is written in C, gets its behaviour directly from C. What
you are seeing is actually the behaviour of C.
> The problem is that I am trying to use the return value of round() as
> the return value of another function, so using Print to tidy it uup
> really doesn't do me any good. Any suggestions?
My suggestion is that instead of rounding the number you convert it
to a string of the required precision:
erikd at coltrane > python
Python 2.1.2 (#1, Jan 18 2002, 18:05:45)
[GCC 2.95.4 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> x = 56.78923
>>> x_as_string = "%.2f" % x
>>> print x_as_string
56.79
Just what you want. Remember however that if you want to operate on the
number using standard arithmetic you need to work on x rather than
x_as_string.
Erik
--
+-----------------------------------------------------------+
Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid)
+-----------------------------------------------------------+
"The whole principle is wrong; it's like demanding that grown men live on
skim milk because the baby can't eat steak."
- author Robert A. Heinlein on censorship.
More information about the Python-list
mailing list