My decimals are too big for %E
so I had to improvize:
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)
Here's an example usage:
>>> n = decimal.Decimal(4.3) ** 12314
>>> print format_decimal(n)
3.39e7800
>>> print '%e' % n
inf