Is there a string format for floats which always starts with 0.x?

Viewed 140

I need a very specific string format for floats in python.

I need all numbers to look like this:

0.313575791515242E+005
0.957214231058814E+000
0.102484469467859E+002
0.251532655168561E-001
0.126906478919395E-002
-0.469847611408333E-003

They always start with a 0.x with 15 digits after the decimal point and end with 3 digits in the exponential.

Can I do this with python? I tried to look at the documentation for string formatting but couldn't figure out how.

I tried with this:

>>> number = 9.622
>>> print(f'{number:.15E}')
9.622000000000000E+00

Which is pretty close, but I still need the leading 0 and 3 digits in the exponent. It has to be like this:

0.962200000000000E+001

Any help is appreciated!

2 Answers

Not sure what is the logic for -/+ before the exponent, but this should give you a good start I hope:

def format(n):
    p = 0
    while n <= -1 or n >= 1:
        n = n / 10.0
        p += 1
    # p could be >= 100 at this point, but we can't do anything
    return "{:.15f}E{:+04d}".format(n, p)

Some glorious hackery. Uses the usual Python scientific notation string formatting, then modifies the result by shifting all of the digits along by 1 and incrementing the exponent by 1.

import re

def sci_after_point(number, significant_digits=15, exponent_digits=3):
    '''Returns the number in scientific notation
    with the significant digits starting immediately after the decimal point.'''

    number_sci = f'{number:.{significant_digits-1}E}'

    sign, lead, point, decimals, E, exponent =\
    re.match(r'([-+]?)(\d)(\.)(\d+)(E)(.*)', number_sci).groups()

    incremented_exponent = int(exponent) + 1
    incremented_exponent = f"{incremented_exponent:+0{exponent_digits + 1}}"

    return sign + '0' + point + lead + decimals + E + incremented_exponent

sci_after_point(-0.313575791515242E005)
Out: '-0.313575791515242E+005'
Related