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+10
5.56572
3.539
22.1523
0
15.9638
0.284024
7.58097
24.3469

Leave a Comment