简体   繁体   中英

Formatting a number with a metric prefix (SI style)

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

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

Example:

I have:

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

I want:

a = 0.000001
b = 0.002
c = 0.0000011

Use the QuantiPhy package. It is a stable well documented and well supported package that is designed to do just what you want.

>>> from quantiphy import Quantity

>>> all = dict(
...     a = Quantity('1u'),
...     b = Quantity('2m'),
...     c = Quantity('1.1u)'
... )
>>> for n, v in all.items():
...     print(f'{n} = {v:<0.7f}')
a = 0.000001
b = 0.002
c = 0.0000011

Quantity subclasses float, so a quantity can be used anywhere a float can be used.

>>> print(sum(all.values()))
0.0020021

When printing it you can retain the SI scale factors. You can also add units to make the quantity more descriptive.

>>> all = dict(
...     a = Quantity('1ug'),
...     b = Quantity('2mg'),
...     c = Quantity('1.1ug)'
... )
>>> for n, v in all.items():
...     print(f'{n} = {v}')
a = 1 ug
b = 2 mg
c = 1.1 ug

It provides many more features as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM