简体   繁体   中英

How are currency units used with Python Pint units?

I would like to do something like this:

import pint
ureg = pint.UnitRegistry()

kg = ureg.kg
USD = ureg.USD  # not the way to do this

weight = 2.3 * kg
price = 1.49 * USD / kg
cost = weight * price
print(f"{cost:~.2f}")

>>> 3.43 USD

The Pint docs including the tutorial are not very clear on this.

The error I get with this code is:

pint.errors.UndefinedUnitError: 'USD' is not defined in the unit registry

So, how do I define USD in the unit registry?

Use ureg.define() to define a new unit. There is no "currency" dimension in the default registry, but you can just add one at the same time you define your unit.

import pint
ureg = pint.UnitRegistry()

ureg.define('USD = currency')

kg = ureg.kg
USD = ureg.USD

weight = 2.3 * kg
price = 1.49 * USD / kg
cost = weight * price
print(f"{cost:~.2f}")  # prints '3.43 USD'

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