How to make Python format floats with certain amou

2019-01-25 06:33发布

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, if it has > 6 significant digits, then output only 6 significant digits.

"A" shows how Python is writing the floats. "B" shows how I want them written. How can I make Python format my numbers in that way?

A:
10188469102.605597
5.5657188485
3.539
22.1522612479
0
15.9638450858
0.284024
7.58096703786
24.3469152383

B:
1.01885e+10
5.56572
3.539
22.1523
0
15.9638
0.284024
7.58097
24.3469

2条回答
等我变得足够好
2楼-- · 2019-01-25 07:09

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
查看更多
家丑人穷心不美
3楼-- · 2019-01-25 07:14

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
查看更多
登录 后发表回答