Python中的科学符号格式 [英] Scientific Notation formatting in Python

查看:104
本文介绍了Python中的科学符号格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得以下格式(输入值始终小于0.1):

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

以此类推.

我正在寻找一些优雅的解决方案.我已经在使用下面给出的自定义功能:

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 the format() function. The format specification mentions it there:

'E'-指数表示法.与'e'相同,不同之处在于它使用大写字母'E'作为分隔符.

'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

这篇关于Python中的科学符号格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆