Search code examples
pythonpython-3.xscipy

Formatting a number with a metric prefix (SI style)


I'm looking for an existing solution, for converting a number with a metric suffix (SI style) to float or int.

Additionally, my initial number with a metric suffix is a string.

Example:

I have:

a = "1u"
b = "2m"
c = "1.1u"

I want:

a = 0.000001
b = 0.002
c = 0.0000011

Solution

  • You can use a dictionary of prefices:

    prefix = {"y":1e-24, "z":1e-21, "a":1e-18, "f":1e-15, "p": 1e-12,
              "n":1e-9, "u":1e-6, "µ":1e-6, "m":1e-3, "c":1e-2, "d":0.1,
              "h":100, "k":1000, "M":1e6, "G":1e9, "T":1e12, "P":1e15,
              "E":1e18, "Z":1e21, "Y":1e24}
    
    def meter(s):
        try:
            # multiply with meter-prefix value
            return float(s[:-1])*prefix[s[-1]]
        except KeyError:
            # no or unknown meter-prefix
            return float(s)
    
    
    for a in ["1u", "2m", "1.1u", "42", "6k"]:
        print(meter(a))
    

    Result:

    1e-06
    0.002
    1.1e-06
    42.0
    6000.0