from decimal import Decimal
'%.2E' % Decimal('40800000000.00000000000000')
# returns '4.08E+10'
In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.
If you want to remove all trailing zeros automatically, you can try:
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'
Answer from eumiro on Stack Overflowfrom decimal import Decimal
'%.2E' % Decimal('40800000000.00000000000000')
# returns '4.08E+10'
In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.
If you want to remove all trailing zeros automatically, you can try:
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'
Here's an example using the format() function:
>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'
Instead of format, you can also use f-strings:
>>> f"{Decimal('40800000000.00000000000000'):.2E}"
'4.08E+10'
official documentation
original format() proposal
Unfortunately, you can not change this default behavior since you can not override the str methods.
However, you can wrap the float, and use the __format__ method:
class MyNumber:
def __init__(self, val):
self.val = val
def __format__(self,format_spec):
ss = ('{0:'+format_spec+'}').format(self.val)
if ( 'E' in ss):
mantissa, exp = ss.split('E')
return mantissa + 'E'+ exp[0] + '0' + exp[1:]
return ss
print( '{0:17.8E}'.format( MyNumber(0.0665745511651039)))
You can use your own formatter and override format_field:
import string
class MyFormatter(string.Formatter):
def format_field(self, value, format_spec):
ss = string.Formatter.format_field(self,value,format_spec)
if format_spec.endswith('E'):
if ( 'E' in ss):
mantissa, exp = ss.split('E')
return mantissa + 'E'+ exp[0] + '0' + exp[1:]
return ss
print( MyFormatter().format('{0:17.8E}',0.00665745511651039) )