Converting floats in Python to Scientific Numbers

Viewed 56

So I have an application in Python that calculates the variable number in the "PV = nRT" chemical equation. The code is like this:

r = 0.082
# Variables
p = float(input('Pressure = '))
p_unit = input('Unit = ')

print('_____________________')

v = float(input('Volume = '))
v_unit = input('Unit = ')

print('_____________________')

n = float(input('Moles = '))

print('_____________________')

t = float(input('Temperature = '))
t_unit = input('Unit = ')

# Unit Conversion
if p_unit == 'bar':
    p = p * 0.987

if v_unit == 'cm3':
    v = v / 1000

if v_unit == 'm3':
    v = v * 1000

if t_unit == 'c':
    t = t + 273

if t_unit == 'f':
    t = ((t - 32) * (5 / 9)) + 273


# Solve Equation
def calc():
    if p == 000:
        return (n * r * t) / v
    if v == 000:
        return (n * r * t) / p
    if n == 000:
        return (p * v) / (r * t)
    if t == 000:
        return (p * v) / (n * r)

and then at the end I run the function to get the result. But the problem is I want to convert the result to a Scientific Number (e.g. 0.005 = 5 x 10^-3). I tried the solution below:

def conv_to_sci(num):
    i = 0
    if num > 10:
        while num > 10:
            num / 10
            i = i - 1
    if num < 10:
        while num < 10:
            num * 10
            i = i + 1
    return num + "x 10^" + i

but it didn't work. Any questions?

2 Answers

I'd just use numpy to get scientific notation

import numpy as np
num = 0.005
num_sc = np.format_float_scientific(num)
>>> num_sc
'5.e-03'

Use str.format

"{:.0e}".format(0.005)

This will print: '5e-03'

Or,

def conv_to_sci(num):
    i = 0
    while int(num) != num:
        num *= 10
        i += 1
    return "{0} x 10^{1}".format(int(num), i)
conv_to_sci(0.005)

Will give: '5 x 10^3'

Related