我如何显示十进制('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。
当前回答
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
其他回答
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(40800000000.00000000000000, '.2E')
#'4.08E+10'
(“E”不区分大小写。你也可以用'.2e')
给定你的数字
x = Decimal('40800000000.00000000000000')
从Python 3开始,
'{:.2e}'.format(x)
是推荐的方法。
E表示你想要科学记数法,.2表示你想要点号后面有两位数字。得到x。xxe±n
我的小数对于%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
请参阅Python字符串格式中的表格,以选择适当的格式布局。在你的例子中是%. 2e。