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