Python Forum

Full Version: Define unit of measure of a number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would like a function or command to define the unit of measure, either MPa (10 ^ 6) or GPa (10 ^ 9).e.g
20,000,000,000.00 > 20GPa
5,000,000.00 > 5MPa
And how might you expect that to look like in code?
def transform(x):
    if x < gpa:
        return(str(int(x/mpa))+"MPa")
    elif x >= gpa:
        return(str(int(x/gpa))+"GPa")

gpa=1000000000
mpa=1000000
value1= 20000000000
value2= 5000000
print(f"{value1} > {transform(value1)}")
print(f"{value2} > {transform(value2)}")
Output:
20000000000 > 20GPa 5000000 > 5MPa
This would also be simple enough to do as a lambda function:
g = lambda x : str(x/1000000)+' MPa' if x<1000000000 else str(x/1000000000)+' GPa'

value1= 20000000000
value2= 5000000

print (g(value1))
print (g(value2))