Search code examples
pythonformattingfloating-point

Python float formatting - like "g", but with more digits


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.


Solution

  • 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.