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

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

    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+10
    5.565719
    3.539000
    22.152261
    0.000000
    15.963845
    0.284024
    7.580967
    24.346915
    

提交回复
热议问题