Search code examples
pythonscientific-notation

Assign scientific notation to variable in Python


I am trying to ask for a float variable, then assign its scientific notation to it and then use that notation in the following operations. As in, I want the program to actually work with the notation, not just return the results in it. I managed to convert variable by using the print function:

def estim(abs(x)):
    a=print("{:.3e}".format(x))
    return a

However that does not actually assign the scientific value to x. I then tried

b=float(a)

but a is None type, so it doesn't work. Any help?

Edit: by scientific notation I mean X.YYYe+Z, example: 31234.34234 -> 3.12e+04


Solution

  • If you do "{:.3e}".format(x) you will get 3 digits after decimal, that is

    >>> a = 31234.34234
    >>> "{:.3e}".format(a)
    '3.123e+04'
    

    To get what you want, you need to do "{:.2e}".format(x).

    >>> "{:.2e}".format(a)
    '3.12e+04'
    >>> float("{:.2e}".format(a))
    31200.0
    

    Converting it back to float will give you the original value

    As a function

    def estim(x):
        x = abs(x)
        a=("{:.2e}".format(x))
        print(a)
        return a
    

    Tip:

    You can use % (It might be deprecated)

    >>> a = 31234.34234
    >>> "%e"%a
    '3.123434e+04'