12
votes

I use "g" for formatting floating point values, but it switches to scientific formatting too soon for me - at the 5th digit:

>>> format(0.0001, "g")
'0.0001'
>>> format(0.00001, "g")
'1e-05'

This seems to be described in the "g" rules (the -4):

The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.

Is there a way to display numbers like "g", but with more digits before switching to scientific notation?

I'm thinking of using ".6f" and stripping trailing zeros, but then I won't be able to see small numbers, which need scientific notation.

3
as per a comment below, ".6g" is valid format string - Eric Blum

3 Answers

9
votes

I had the same question.

Looking at the Python documentation it seems that g also supports precision values:

General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.

I don't know, why the other answers don't use this and I am not very experienced in Python, but it works.

This can be simply achieved by using format(0.00001, '.10g') where 10 is the precision you want.

4
votes
from math import log10

if log10(n) < -5:
    print "%e" % n
else:
    print "%f" % n

EDIT: it's also possible to put it on a single line:

("%e" if log10(n) < -5 else "%f") % n

If n might be negative, then use log10(abs(n)) in place of log10(n).

EDIT 2: Improved based on Adal's comments:

"%e" % n if n and log10(abs(n)) < -5 else ("%f" % n).rstrip("0")

This will print 0 as "0."--if you want another representation like "0" or "0.0", you'll need to special case it with a separate if.

3
votes

If you're using Python 2.7 you can do the following using it's advanced string formatting mini-language:

>>> '{number:.{width}f}'.format(number=0.000000000001, width=20)
'0.00000000000100000000'

You can then specify the required value of number and width dynamically.