如何得到如下格式(输入值总是小于0.1):
> formatting(0.09112346)
0.91123E-01
> formatting(0.00112346)
0.11234E-02
等等。
我正在寻找一些优雅的解决方案。我已经在使用下面给出的自定义函数:
def formatting(x, prec=5):
tup = x.as_tuple()
digits = list(tup.digits[:prec])
dec = ''.join(str(i) for i in digits)
exp = x.adjusted()
return '0.{dec}E{exp}'.format(dec=dec, exp=exp)
最佳答案
您可以使用 format()
功能。 The format specification在那里提到它:
'E' - Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character.
>>> print('{:.5E}'.format(0.09112346))
9.11235E-02
>>> print('{:.5E}'.format(0.00112346))
1.12346E-03
但是,它与您在答案中的输出不太一样。如果以上不满意,那么你可以使用自定义函数来帮助(我不是最擅长的,所以希望它没问题):
def to_scientific_notation(number):
a, b = '{:.4E}'.format(number).split('E')
return '{:.5f}E{:+03d}'.format(float(a)/10, int(b)+1)
print(to_scientific_notation(0.09112346))
# 0.91123E-01
print(to_scientific_notation(0.00112346))
# 0.11234E-02
关于python - Python 中的科学记数法格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53274821/