roam/20210806111448-working_with_currencies.org

35 lines
1,020 B
Org Mode
Raw Permalink Normal View History

2021-08-06 16:58:50 +00:00
:PROPERTIES:
:ID: 36fa073d-4b34-4b2b-bf96-0994a44df61e
:END:
2021-08-06 17:21:42 +00:00
#+title: Working with currency units in Python
2021-08-06 16:58:50 +00:00
- https://simple.wikipedia.org/wiki/ISO_4217
2021-08-06 17:21:42 +00:00
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]].
2023-12-12 20:07:25 +00:00
#+begin_src python :exports both :eval no-export
2021-08-06 16:58:50 +00:00
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:
2021-08-06 17:04:21 +00:00
: 19.99