python - Python 中的科学记数法格式

标签 python formatting scientific-notation

如何得到如下格式(输入值总是小于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/

相关文章:

cocoa - NSDictionary objectForKey/valueForKey 已格式化?

layout - 更改 latex 文档中间的纸张尺寸?

parsing - 从文本文件lua中解析科学数字

python - python 中的线性系统连接与 scipy

python - 使用python计算一个特殊的极限

python - 在 IPython Notebook (Bokeh) 中绘制大型数据集

Oracle 'printf' 等效

python - 将 python 十进制格式化为 [-.0-9]*,没有尾随零,保值

ieee-754 - 将科学记数法的十进制数转换为 IEEE 754

python - 在 Sublime Text 中使用 Pylinter 时出现导入错误