Scientific Notation formatting in Python

安稳与你 提交于 2019-12-12 19:18:04

问题


How can get following formatting (input values are always less than 0.1):

> formatting(0.09112346)
0.91123E-01
> formatting(0.00112346)
0.11234E-02

and so on.

I am looking for some elegant solution. I am already using a custom function given below:

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)

回答1:


You can use the format() function. The format specification mentions it there:

'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

However it isn't quite like the output you have in your answer. If the above is not satisfactory, then you might use a custom function to help (I'm not the best at this, so hopefully it's ok):

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


来源:https://stackoverflow.com/questions/53274821/scientific-notation-formatting-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!