Display a decimal in scientific notation
How can I display this:
Decimal('40800000000.00000000000000') as '4.08E+10'?
I've tried this:
>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'
But it has those extra 0's.
Solution 1:
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'
Solution 2:
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
Solution 3:
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