我如何显示十进制('40800000000.00000000000000')为'4.08E+10'?

我试过了:

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

但是它有多余的0。


当前回答

没有人提到.format方法的缩写形式:

至少需要Python 3.6

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

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

其他回答

要将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()。

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

PYTHON 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
# =====================================

或无进口

# 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))
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'

请参阅Python字符串格式中的表格,以选择适当的格式布局。在你的例子中是%. 2e。

下面是一个使用format()函数的例子:

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

除了format,你还可以使用f-strings:

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

官方文档 原始格式()提案