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

后端 未结 3 900
醉梦人生
醉梦人生 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:36

    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+10
    5.56572
    3.53900
    22.1523
    0.00000
    15.9638
    0.284024
    7.58097
    24.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.

提交回复
热议问题