If you must do this, then the easiest way will be to just use the built in formating, and then just replace the e+05 or e-12 with whatever you'd rather have:
def sci_notation(number, sig_fig=2):
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
a, b = ret_string.split("e")
# remove leading "+" and strip leading zeros
b = int(b)
return a + " * 10^" + str(b)
print sci_notation(10000, sig_fig=4)
# 1.0000 * 10^4
Answer from will on Stack OverflowIf you must do this, then the easiest way will be to just use the built in formating, and then just replace the e+05 or e-12 with whatever you'd rather have:
def sci_notation(number, sig_fig=2):
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
a, b = ret_string.split("e")
# remove leading "+" and strip leading zeros
b = int(b)
return a + " * 10^" + str(b)
print sci_notation(10000, sig_fig=4)
# 1.0000 * 10^4
Use the new string formatting. The old style you're using is deprecated anyway:
In [1]: "{0:.{1}e}".format(3.0, 5)
Out[1]: '3.00000e+00'
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'
official documentation
original format() proposal
I got 2.7 * 106, which is 2700000.0 and I need it to be 270 * 104
there is a way to get this scientific notation? i really need this
I am writing a simple program to help me do my semiconductors homework. I would like to use the input() function to have the user input a string in the format "1e15" for instance, meaning 1x10^15. How can I convert that string into an integer?
Is there a way to convert a massive int to scientific notation? I tried using
return "{:.2e}".format(input)
but it says "OverflowError: int too large to convert to float"