Convert a float in scientific notation to a "d.dd x 10^(-n)"

Viewed 71

I'm building a calculator to calculate some chemistry related calculations. So most of the results will be extremely small values.

An example result is 4.840909814726882e-09.

How do I display this value in a format like 4.84 x 10^(-9)?

2 Answers

try this:

format(4.840909814726882e-09, '.2e').replace('e', ' x 10^(') + ')'

Output:
4.84 x 10^(-09)
It's not exactly the result you wanted but it's simple.

Also there is:

def my_format(num):
    s = format(num, '.2e')
    base, exp = s.split('e')
    return f'{base} x 10^({int(exp)})'

Output:

>>> my_format(4.840909814726882e-09)
'4.84 x 10^(-9)'

which is more coplicated but it's exectly the result you wanted.

How do I display the value to a format like 4.84 x 10^(-9) ?

By hand, that is not a format supported by Python.

Although if you just want to "round off" the number because you neither have nor need 15 significant digits, then you can use format specifiers, and either the g presentation type:

>>> format(v, 'g')
'4.84091e-09'

or an explicit precision:

>>> format(v, '.3')
'4.84e-09'
Related