简体   繁体   English

强制前导零的python科学记数法

[英]python scientific notation with forced leading zero

I want to have Python2.7 print out floating point numbers in scientific notation, forced to start with 0. For instance, assume我想让 Python2.7 以科学记数法打印浮点数,强制从 0 开始。例如,假设

a=1234567890e12
print '{:22.16E}'.format(a)
1.2345678900000000E+21

However, I want a print output that looks like:但是,我想要一个看起来像的打印输出:

0.1234567890000000E+22

Notice that the exponent is raised by one since the desired output is forced to a leading zero.请注意,指数增加了 1,因为所需的输出被强制为前导零。 How can I achieve this?我怎样才能做到这一点? Thanks.谢谢。

The fortranformat package will do what you are looking for. fortranformat 包将满足您的需求。

import fortranformat as ff

a=1234567890e12
lineformat = ff.FortranRecordWriter('(1E26.16)')
lineformat.write([a])

Output:输出:

'    0.1234567890000000E+22'

Handles E- as well.也处理 E-。

def fortranFormat(n):
    a = '{:.4E}'.format(float(n))
    e = a.find('E')
    return '0.{}{}{}{:02d}'.format(a[0],a[2:e],a[e:e+2],abs(int(a[e+1:])*1+1))

print(fortranFormat('60.505'))
print(fortranFormat('74.705'))
print(fortranFormat('2.000000E-09'))

output:输出:

0.60505E+02
0.74705E+02
0.20000E-08

Well, since what you want to do is not "standard" scientific notation, I'm not sure if there is a simple call to do this.好吧,由于您想要做的不是“标准”科学记数法,我不确定是否有一个简单的调用来执行此操作。 Here is a hack, however, that will work但是,这是一个 hack,它会起作用

a = 1234567890e12
A = str(a)
exp = A.find('e+')
converted = '0.' + A[0] + A[2:exp] + 'e+' + str(int(A[exp+2:])+1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM