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
Andrej Jan 12 '15 at 10:19 2015-01-12 10:19
source share