Convert to scientific notation in Python (A × 10^B)

 ̄綄美尐妖づ 提交于 2019-12-14 03:12:03

问题


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):

  1. x='%.%de' %(num,sig)

    TypeError: not all arguments converted during string formatting

  2. x='%d.%de' %(num,sig)

    x = 99999.2e (incorrect output)

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!