问题
I was using this question to help me create a Scientific Notation function, however instead of 4.08E+10
I wanted this: 4.08 x 10^10
. So I made a working function like so:
def SciNotation(num,sig):
x='%.2e' %num #<-- Instead of 2, input sig here
x= x.split('e')
if (x[1])[0] == "-":
return x[0]+" x 10^"+ x[1].lstrip('0')
else:
return x[0]+" x 10^"+ (x[1])[1:].lstrip('0')
num = float(raw_input("Enter number: "))
sig = raw_input("Enter significant figures: ")
print SciNotation(num,2)
This function, when given an input of 99999
will print an output of 1.00 x 10^5
(2 significant figures). However, I need to make use of my sig
variable (# of significant figures inputted by user). I know I have to input the sig
variable into Line 2 of my code but I can't seem to get to work.
So far I have tried (with inputs num=99999, sig=2):
x='%.%de' %(num,sig)
TypeError: not all arguments converted during string formatting
x='%d.%de' %(num,sig)
x = 99999.2e (incorrect output)
x='{0}.{1}e'.format(num,sig)
x = 99999.0.2e (incorrect output)
Any help would be appreciated!
回答1:
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'
回答2:
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")
b = int(b) #removed leading "+" and strips leading zeros too.
return a + " * 10^" + str(b)
print sci_notation(10000, sig_fig=4) # 1.0000 * 10^4
来源:https://stackoverflow.com/questions/29260893/convert-to-scientific-notation-in-python-a-%c3%97-10b