Float to String

Mark Dickinson mdickinson at enthought.com
Wed Oct 31 11:39:53 EDT 2012


 <andrew.mackeith <at> 3ds.com> writes:

> When formatting a float using the exponential format, the rounding is
> different in Python-2.6 and Python-2.7. See example below.  Is this
> intentional?

Yes, in a sense.  Python <= 2.6 uses the OS-provided functionality (e.g., the C
library's strtod, dtoa and sprintf functions) to do float-to-string and
string-to-float conversions, and hence behaves differently from platform to
platform.  In particular, it's common for near halfway cases (like the one
you're looking at here) and tiny numbers to give different results on different
platforms.  Python >= 2.7 has its own built-in code for performing
float-to-string and string-to-float conversions, so those conversions are
platform- independent and always correctly rounded.  (Nitpick: it's still
theoretically possible for Python 2.7 to use the OS code if it can't determine
the floating-point format, or if it can't find a way to ensure the proper FPU
settings, but I don't know of any current platforms where that's the case.)

> Is there any way of forcing the Python-2.6 behavior (for compatibility
> reasons when testing)?

Not easily, no.

--
Mark





More information about the Python-list mailing list