Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

python - Use fixed exponent in scientific notation

Consider the following Python snippet:

for ix in [0.02, 0.2, 2, 20, 200, 2000]:
    iss = str(ix) + "e9"
    isf = float(iss)
    print(iss + "=> " + ("%04.03e" % isf) + " (" + str(isf) + ")")

It generates the following output:

0.02e9  => 2.000e+07 (20000000.0)
0.2e9   => 2.000e+08 (200000000.0)
2e9     => 2.000e+09 (2000000000.0)
20e9    => 2.000e+10 (20000000000.0)
200e9   => 2.000e+11 (2e+11)
2000e9  => 2.000e+12 (2e+12)

Is it possible to "go back" somehow? That is:

2.000e+07 => 0.02e9 
2.000e+08 => 0.2e9
2.000e+09 => 2e9    
2.000e+10 => 20e9   
2.000e+11 => 200e9  
2.000e+12 => 2000e9

... I'd specify I want the exponent to be e+09; and then whatever number I throw at this hypothetic function, returns the number value in that exponent? Would it be possible to specify zero padding for both the whole and the decimal part in each case? (i.e. 000.0200e9 and 020.0000e9)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Format it yourself (see Format Specification Mini-Language):

for ix in [.02e9, .2e9, 2e9, 20e9, 200e9, 2000e9]:
    print('{:.3e} => {:0=8.3f}e9'.format(ix, ix / 1e9))

Output

2.000e+07 => 0000.020e9
2.000e+08 => 0000.200e9
2.000e+09 => 0002.000e9
2.000e+10 => 0020.000e9
2.000e+11 => 0200.000e9
2.000e+12 => 2000.000e9

Explanation

{:0=8.3f} means "zero-pad, pad between the sign and the number, total field width 8, 3 places after the decimal, fixed point format".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...