Question

I want to have Python2.7 print out floating point numbers in scientific notation, forced to start with 0. For instance, assume

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. How can I achieve this? Thanks.

Was it helpful?

Solution 3

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

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

OTHER TIPS

The fortranformat package will do what you are looking for.

import fortranformat as ff

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

Output:

'    0.1234567890000000E+22'

Handles E- as well.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top