Scientific Notation formatting in Python

后端 未结 2 1386
-上瘾入骨i
-上瘾入骨i 2021-01-05 06:38

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


        
相关标签:
2条回答
  • 2021-01-05 06:58

    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
    
    0 讨论(0)
  • 2021-01-05 07:10

    In Python 3.6+, you could also use f-strings. For example:

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

    It uses the same syntax as str.format(), given in the Format Specification Mini-Language section.

    0 讨论(0)
提交回复
热议问题