float to str help

Steve Holden sholden at holdenweb.com
Thu Jul 19 13:51:20 EDT 2001


"Bryan Webb" <bww00 at amdahl.com> wrote in message
news:9j6tva$9mb at dispatch.concentric.net...
> Hi,
>     In converting a float (5.661706091586558e+240) to a string using str()
I
> come up with 5.6617060916+240 . I checked the string variable in the
> debugger. I need the full precicsion. I know its probably simple but this
> red hair is causing me problems.
>
Using string formatting will give you as much precision as is available. Of
course there is no guarantee that the interpreter will have been able to
represent your literal exactly as a floating point number, though it will
get pretty close:

>>> x = 5.661706091586558e+240
>>> print "%.25e" % x
5.6617060915865581000000000e+240
>>>

This isn't just because of the number of digits in your literal. The same is
true of many "apparently simple" numbers:

>>> y = 0.1
>>> print "%.25e" % y
1.0000000000000001000000000e-001
>>>

Conversion of decimal constants to binary floating-point is by its nature
often bound to be inexact, as these two examples show.

Hope this helps.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list