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

后端 未结 3 887
醉梦人生
醉梦人生 2020-12-03 04:48

I want my Python (2.4.3) output numbers to have a certain format. Specifically, if the number is a terminating decimal with <= 6 significant digits, show it all. However,

3条回答
  •  [愿得一人]
    2020-12-03 05:32

    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
    

提交回复
热议问题