Display a decimal in scientific notation Display a decimal in scientific notation python python

Display a decimal in scientific notation


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'


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'


Given your number

x = Decimal('40800000000.00000000000000')

Starting from Python 3,

'{:.2e}'.format(x)

is the recommended way to do it.

e means you want scientific notation, and .2 means you want 2 digits after the dot. So you will get x.xxE±n