Python Forum
Define unit of measure of a number - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Define unit of measure of a number (/thread-21800.html)



Define unit of measure of a number - doug2019 - Oct-15-2019

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


RE: Define unit of measure of a number - Larz60+ - Oct-15-2019

And how might you expect that to look like in code?


RE: Define unit of measure of a number - baquerik - Oct-15-2019

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



RE: Define unit of measure of a number - jefsummers - Oct-15-2019

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))