将科学计数法中的尾数从0-1改为1-10

问题描述 投票:0回答:1

我想格式化一个数字,使尾数在0和1之间,而不是科学记数法中的1和10之间。

例如;

a=7.365
print("{:.6e}".format(a))

这将输出

7.365000e+00
,但我希望它是
0.736500e+01

python python-2.7
1个回答
0
投票

我想你总是可以尝试构建你自己的预格式化字符串。 (不过不知道这在 Python 2.7 中是否有效)。

import math

def fixit( x, n ):
   if x == 0.0: return f" {x:.{n}e}"

   s = ' ' if x >= 0 else '-'
   y = math.log10( abs(x) )
   m = math.floor(y) + 1
   z = 10 ** ( y - m )
   return s + f"{z:.{n}f}e{m:+03d}"

for x in [ -7635, -763.5, -76.35, -7.635, -0.7635, -0.07635, -0.007635, 0.007635, 0.07635, 0.7635, 7.635, 76.35, 763.5, 7635 ]:
    print( fixit( x, 6 ) )
for x in [ -10, -1, -0.1, -0.01, 0.0, 0.01, 0.1, 1, 10 ]:
    print( fixit( x, 6 ) )

输出:

-0.763500e+04
-0.763500e+03
-0.763500e+02
-0.763500e+01
-0.763500e+00
-0.763500e-01
-0.763500e-02
 0.763500e-02
 0.763500e-01
 0.763500e+00
 0.763500e+01
 0.763500e+02
 0.763500e+03
 0.763500e+04
-0.100000e+02
-0.100000e+01
-0.100000e+00
-0.100000e-01
 0.000000e+00
 0.100000e-01
 0.100000e+00
 0.100000e+01
 0.100000e+02
© www.soinside.com 2019 - 2024. All rights reserved.