簡體   English   中英

Python 中的科學記數法格式

[英]Scientific Notation formatting in Python

如何獲得以下格式(輸入值始終小於 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()函數。 格式規范在那里提到了它:

'E' - 指數符號。 與 'e' 相同,但它使用大寫的 'E' 作為分隔符。

>>> 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 3.6+ 中,您還可以使用f-strings 例如:

In [31]: num = 0.09112346

In [32]: f'{num:.5E}'
Out[32]: '9.11235E-02'

它使用與str.format()相同的語法,在格式規范迷你語言部分給出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM