18

考虑以下 Python 片段:

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

它生成以下输出:

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)

有没有可能以某种方式“回去”?那是:

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

...我会指定我希望指数为e+09; 然后我在这个假设函数中抛出的任何数字都返回该指数中的数值?是否可以在每种情况下为整体和小数部分指定零填充?(即000.0200e9020.0000e9)?

4

3 回答 3

27

自己格式化(参见Format Specification Mini-Language):

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

输出

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

解释

{:0=8.3f}表示“零填充,符号和数字之间的填充,总字段宽度 8,小数点后 3 位,定点格式”。

于 2011-11-24T21:01:01.290 回答
2

嗯,明白了:

for ix in [0.02, 0.2, 2, 20, 200, 2000]:
  iss=str(ix) + "e9"
  isf=float(iss)
  isf2=isf/float("1e9")
  isf2s = ("%04.03f" % isf2) + "e9"
  print(iss + "\t=> " + ("%04.03e" % isf ) + " (" + str(isf) + ")" + " -> " + isf2s )

...给出:

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

抱歉发帖,
干杯!

于 2011-11-24T21:00:12.103 回答
1

对于那些年后仍然遇到的人......

你可以使用 python 的 Decimal 和 quantize

https://docs.python.org/3.6/library/decimal.html#decimal.Decimal.quantize

于 2019-04-20T18:12:00.647 回答