简体   繁体   English

Python 中的科学记数法格式

[英]Scientific Notation formatting in Python

How can get following formatting (input values are always less than 0.1):如何获得以下格式(输入值始终小于 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)

You can use theformat() function.您可以使用format()函数。 The format specification mentions it there: 格式规范在那里提到了它:

'E' - Exponent notation. 'E' - 指数符号。 Same as 'e' except it uses an upper case 'E' as the separator character.与 'e' 相同,但它使用大写的 'E' 作为分隔符。

>>> 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

In Python 3.6+, you could also use f-strings .在 Python 3.6+ 中,您还可以使用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.它使用与str.format()相同的语法,在格式规范迷你语言部分给出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM