[Python-3000] str.format() -- poss. code or doc bug?

Mark Summerfield mark at qtrac.eu
Fri Nov 30 12:20:12 CET 2007


I'm using Python 30a.

The docs for str.format()'s 'g' format say
    "General format. This prints the number as a fixed-point number,
    unless the number is too large, in which case it switches to 'e'
    exponent notation."
The fixed-point format uses the 'f' character.

But this does not seem to happen in practice:

>>> "[{0:12.4e}] [{0:12.4f}] [{0:12.4g}]".format(10**4 * math.pi)
'[  3.1416e+04] [  31415.9265] [   3.142e+04]'
>>> "[{0:12.4e}] [{0:12.4f}] [{0:12.4g}]".format(10**3 * math.pi)
'[  3.1416e+03] [   3141.5927] [        3142]'

I thought this was a bug in Python 3, but Python 2 does the same thing:

>>> n = 10**4 * math.pi
>>> m = 10**3 * math.pi
>>> "[%12.4e] [%12.4f] [%12.4g]" % (n, n, n)
'[  3.1416e+04] [  31415.9265] [   3.142e+04]'
>>> "[%12.4e] [%12.4f] [%12.4g]" % (m, m, m)
'[  3.1416e+03] [   3141.5927] [        3142]'

Python 2's docs are different from Python 3's regarding 'g' format:
    "Floating point format. Uses exponential format if exponent is
    greater than -4 or less than precision, decimal format otherwise."
There is no "decimal format", but there is "Signed integer decimal"
format which is what seems to being used.

So is this a doc bug?

BTW I notice that decimal.Decimal() numbers can't be used with the 'e',
'f', or 'g' formats. I know that these numbers aren't floating-point
under the hood, but this still seems a bit counter-intuitive to me.

Mark Summerfield, Qtrac Ltd., www.qtrac.eu

More information about the Python-3000 mailing list