anon
anon

Reputation:

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

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!

Upvotes: 1

Views: 9329

Answers (2)

will
will

Reputation: 10650

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

Upvotes: 8

Carsten
Carsten

Reputation: 18446

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'

Upvotes: 1

Related Questions