我如何显示十进制('40800000000.00000000000000')为'4.08E+10'?
我试过了:
>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'
但是它有多余的0。
我如何显示十进制('40800000000.00000000000000')为'4.08E+10'?
我试过了:
>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'
但是它有多余的0。
当前回答
请参阅Python字符串格式中的表格,以选择适当的格式布局。在你的例子中是%. 2e。
其他回答
我更喜欢Python 3。x。
cal = 123.4567
print(f"result {cal:.4E}")
4表示浮动部分显示了多少位数字。
cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")
这是一个“简单”答案和评论的综合列表。
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))
这对我来说效果最好:
import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10
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
下面是一个使用format()函数的例子:
>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'
除了format,你还可以使用f-strings:
>>> f"{Decimal('40800000000.00000000000000'):.2E}"
'4.08E+10'
官方文档 原始格式()提案