Python:一种科学记数法

时间:2016-12-07 06:48:15

标签: floating-point python-3.5 number-formatting scientific-notation

我有一系列浮点数,我需要以特定格式打印出来,非常类似于科学记数法。 鉴于数字-345.678,科学记数法会给我-3.45678E2,但我需要输出-.345678D03。具体来说,我不能在小数点左边有任何数字。在Python 3中有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

我不确定您的格式的完整详细信息,但以下内容应该可以正常工作或轻松修改:

from decimal import Decimal

def sci_str(dec):
    return ('{:.' + str(len(dec.normalize().as_tuple().digits) - 1) + 'E}').format(dec)

def mod_sci_str(x):
    s = sci_str(10*Decimal(str(x)))
    s = s.replace('E+','D0')
    s = s.replace('E-','D0-')
    s = s.replace('.','')
    if s.startswith('-'):
        return '-.' + s[1:]
    else:
        return '.' + s

由于@MikeM在这个问题中,函数sci_str是一个聪明的实用程序

例如:

>>> mod_sci_str(-345.678)
'-.345678D03'
>>> mod_sci_str(345.678)
'.345678D03' 
>>> mod_sci_str(0.0034)
'.34D0-2'