208

我怎样才能显示这个:

十进制('40800000000.00000000000000')为'4.08E+10'?

我试过这个:

>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'

但它有那些额外的0。

4

13 回答 13

188
from decimal import Decimal

'%.2E' % Decimal('40800000000.00000000000000')

# returns '4.08E+10'

在您的 '40800000000.00000000000000' 中,有许多与任何其他数字具有相同含义的重要零。这就是为什么你必须明确告诉你想停在哪里。

如果要自动删除所有尾随零,可以尝试:

def format_e(n):
    a = '%E' % n
    return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]

format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'

format_e(Decimal('40000000000.00000000000000'))
# '4E+10'

format_e(Decimal('40812300000.00000000000000'))
# '4.08123E+10'
于 2011-08-02T14:19:57.293 回答
151

format()这是使用该函数的示例:

>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'

除了格式,您还可以使用f-strings

>>> f"{Decimal('40800000000.00000000000000'):.2E}"
'4.08E+10'
于 2013-11-08T16:44:41.577 回答
51

给定你的号码

x = Decimal('40800000000.00000000000000')

从 Python 3 开始,

'{:.2e}'.format(x)

是推荐的方法。

e表示您需要科学记数法,并且.2表示您需要点后的 2 位数字。所以你会得到x.xxE±n

于 2017-03-12T15:47:55.273 回答
41

没有人提到该.format方法的简短形式:

至少需要 Python 3.6

f"{Decimal('40800000000.00000000000000'):.2E}"

(我相信和Cees Timmerman一样,只是短了一点)

于 2018-02-26T10:38:18.280 回答
12

这是“简单”答案和评论的综合列表。

蟒蛇3

from decimal import Decimal

x = '40800000000.00000000000000'
# Converted to Float
x = Decimal(x)

# ===================================== # `Dot Format`
print("{0:.2E}".format(x))
# ===================================== # `%` Format
print("%.2E" % x)
# ===================================== # `f` Format
print(f"{x:.2E}")
# =====================================
# ALL Return: 4.08E+10
print((f"{x:.2E}") == ("%.2E" % x) == ("{0:.2E}".format(x)))
# True
print(type(f"{x:.2E}") == type("%.2E" % x) == type("{0:.2E}".format(x)))
# True
# =====================================

IMPORT没有

# NO IMPORT NEEDED FOR BASIC FLOATS
y = '40800000000.00000000000000'
y = float(y)

# ===================================== # `Dot Format`
print("{0:.2E}".format(y))
# ===================================== # `%` Format
print("%.2E" % y)
# ===================================== # `f` Format
print(f"{y:.2E}")
# =====================================
# ALL Return: 4.08E+10
print((f"{y:.2E}") == ("%.2E" % y) == ("{0:.2E}".format(y)))
# True
print(type(f"{y:.2E}") == type("%.2E" % y) == type("{0:.2E}".format(y)))
# True
# =====================================

比较

# =====================================
x
# Decimal('40800000000.00000000000000')
y
# 40800000000.0

type(x)
# <class 'decimal.Decimal'>
type(y)
# <class 'float'>

x == y
# True
type(x) == type(y)
# False

x
# Decimal('40800000000.00000000000000')
y
# 40800000000.0

所以对于 Python 3,你现在可以在这三个中的任何一个之间切换。

我的最爱:

print("{0:.2E}".format(y))
于 2019-10-27T04:29:41.340 回答
11

查看Python 字符串格式中的表格以选择正确的格式布局。在你的情况下,它是%.2E.

于 2011-08-02T14:22:37.450 回答
4

我的小数太大了,%E所以我不得不即兴发挥:

def format_decimal(x, prec=2):
    tup = x.as_tuple()
    digits = list(tup.digits[:prec + 1])
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in digits[1:])
    exp = x.adjusted()
    return '{sign}{int}.{dec}e{exp}'.format(sign=sign, int=digits[0], dec=dec, exp=exp)

这是一个示例用法:

>>> n = decimal.Decimal(4.3) ** 12314
>>> print format_decimal(n)
3.39e7800
>>> print '%e' % n
inf
于 2013-01-06T22:06:10.390 回答
4

这对我最有效:

import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10
于 2016-05-12T08:09:23.887 回答
3

要将 Decimal 转换为科学记数法,而不需要在格式字符串中指定精度,并且不包括尾随零,我目前正在使用

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

print( sci_str( Decimal('123.456000') ) )    # 1.23456E+2

要保留任何尾随零,只需删除normalize().

于 2014-02-26T11:37:33.533 回答
3

我更喜欢 Python 3.x 的方式。

cal = 123.4567
print(f"result {cal:.4E}")

4表示浮动部分显示了多少位。

cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")
于 2019-09-11T03:33:46.803 回答
1

这是我能找到的最简单的一个。

format(40800000000.00000000000000, '.2E')
#'4.08E+10'

(“E”不区分大小写。您也可以使用“.2e”)

于 2020-04-05T22:05:11.213 回答
0
def formatE_decimal(x, prec=2):
    """ Examples:
    >>> formatE_decimal('0.1613965',10)
    '1.6139650000E-01'
    >>> formatE_decimal('0.1613965',5)
    '1.61397E-01'
    >>> formatE_decimal('0.9995',2)
    '1.00E+00'
    """
    xx=decimal.Decimal(x) if type(x)==type("") else x 
    tup = xx.as_tuple()
    xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
    tup = xx.as_tuple()
    exp = xx.adjusted()
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in tup[1][1:prec+1])   
    if prec>0:
        return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
    elif prec==0:
        return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
    else:
        return None
于 2015-01-12T10:19:08.093 回答
0

添加更新的答案以显示如何e notation仅适用于小数字

value = 0.1
a = "{:,}".format(value) if value >= 0.001 else "{:,.3e}".format(value)
print(a) # 0.1

value = 0.00002488
a = "{:,}".format(value) if value >= 0.001 else "{:,.3e}".format(value)
print(a) # 2.488e-05
于 2021-10-14T10:41:38.507 回答