浮点数是否有始终以0.x开头的字符串格式?

时间:2018-09-19 13:06:16

标签: python string python-3.x format string-formatting

对于Python中的浮点数,我需要一种非常特定的字符串格式。

我需要所有数字看起来像这样:

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

它们总是以0.x开头,小数点后有15位数字,以3位数结尾。

我可以使用python吗?我试图查看字符串格式的文档,但不知道如何。

我尝试过:

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

这很接近,但是我仍然需要指数中的前0和3位数字。一定是这样的:

0.962200000000000E+001

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

不确定在指数出现前-/+的逻辑是什么,但是我希望这可以为您提供一个良好的开端:

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)

答案 1 :(得分:0)

一些光荣的黑客。使用通常的Python科学计数法字符串格式,然后通过将所有数字都移位1并将指数递增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'