:PROPERTIES: :ID: 36fa073d-4b34-4b2b-bf96-0994a44df61e :END: #+title: Working with currency units in Python - https://simple.wikipedia.org/wiki/ISO_4217 An example of converting between sub-units and base units in [[id:cda9c620-fec5-4549-b979-22fc06819d77][Python]] as defined in [[id:bb3ab7e4-8824-4c32-bc74-e5b900d6e4d1][ISO 4217: Currency Codes]]. #+begin_src python :exports both :eval no-export 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) #+end_src #+RESULTS: : 19.99