roam/20210806111448-working_with...

1020 B

Working with currency units in Python

An example of converting between sub-units and base units in Python as defined in ISO 4217: Currency Codes.

  from decimal import Decimal

  import pint
  from iso_4217 import define_currency_units

  currency_units = define_currency_units(pint.UnitRegistry(non_int_type=Decimal))


  def to_base_units(currency: str, amount: int) -> Decimal:
      """Convert an amount in a currency's smallest denomination to its base.

      e.g. a USD value in its lowest denomination (cents) as 1999 would convert to
      19.99 (dollars).
      """
      subunit = currency_units[f'{currency.upper()}s']
      return (subunit * amount).to_base_units().magnitude


  return to_base_units('USD', 1999)
19.99