是否有一种始终以 0.x 开头的浮点数字符串格式?
Is there a string format for floats which always starts with 0.x?
我需要一个非常具体的字符串格式用于 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
感谢任何帮助!
不确定指数前 -/+
的逻辑是什么,但我希望这会给你一个好的开始:
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)
一些光荣的黑客技术。使用通常的 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'
我需要一个非常具体的字符串格式用于 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
感谢任何帮助!
不确定指数前 -/+
的逻辑是什么,但我希望这会给你一个好的开始:
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)
一些光荣的黑客技术。使用通常的 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'