How to make Python format floats with certain amount of significant digits? How to make Python format floats with certain amount of significant digits? python python

How to make Python format floats with certain amount of significant digits?


You'll want the g modifier for format that drops insignificant zeroes;

>>> "{0:.6g}".format(5.5657188485)'5.56572'>>> "{0:.6g}".format(3.539)'3.539'

Sorry, my update also includes the fact that I am restricted to using Python 2.4.3, which does not have format() function.

The format specifiers work even without the .format() function:

>>> for i in a:...    print '%.6g' % (i,)...1.01885e+105.565723.53922.1523015.96380.2840247.5809724.3469


There is a way to retain trailing zeros so that it consistently shows the number of significant digits. Not exactly what OP wanted, but probably useful to many.

a = [10188469102.605597,5.5657188485,3.539,22.1522612479,0,15.9638450858,0.284024,7.58096703786,24.3469152383]for i in a:    print("{:#.6g}".format(i))

Output

1.01885e+105.565723.5390022.15230.0000015.96380.2840247.5809724.3469

Note that this will only work with the format function and not with % operator.

According to the docs:

The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float, complex and Decimal types.

'g': General format ... insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.


try this way

a=[10188469102.605597,5.5657188485,3.539,22.1522612479,0,15.9638450858,0.284024,7.58096703786,24.3469152383] for i in a:    if i >100:        print '{:.6e}'.format(i)    else:        print '{:.6f}'.format(i)

for lower version of python

for i in a:    if i >100:        print '%6e'%i    else:        print '%6f'%i

output

1.018847e+105.5657193.53900022.1522610.00000015.9638450.2840247.58096724.346915