aboutsummaryrefslogtreecommitdiffstats
path: root/currencies.py
diff options
context:
space:
mode:
authorPinapelz <yukais@pinapelz.com>2024-01-28 21:13:08 -0800
committerPinapelz <yukais@pinapelz.com>2024-01-28 21:13:08 -0800
commit6255f111989d75860b2b0cc136fc8d1444ffb57b (patch)
tree1e95199d23421e80752d64ee78d42416e955513f /currencies.py
Initial commit
Diffstat (limited to 'currencies.py')
-rw-r--r--currencies.py26
1 files changed, 26 insertions, 0 deletions
diff --git a/currencies.py b/currencies.py
new file mode 100644
index 0000000..d95df95
--- /dev/null
+++ b/currencies.py
@@ -0,0 +1,26 @@
+import requests
+import json
+
+class CurrencyConv:
+ def __init__(self, currency_json_url: str="https://open.er-api.com/v6/latest/USD"):
+ try:
+ self._currency_data = json.loads(requests.get(currency_json_url).text)
+ except:
+ raise Exception("Unable to load currency data from " + currency_json_url)
+ self._currency_rates = self._currency_data["rates"]
+
+ def convert(self, amount: float, from_currency: str, to_currency: str) -> float:
+ # handle some conversion errors
+ from_currency = from_currency.replace("\xa0", "").strip().upper()
+ from_currency= from_currency.replace("₱", "PHP")
+ from_currency = from_currency.replace("¥", "JPY")
+ try:
+ if from_currency == to_currency:
+ return amount
+ return amount * self._currency_rates[to_currency] / self._currency_rates[from_currency]
+ except:
+ raise Exception("Unable to convert from " + from_currency + " to " + to_currency)
+
+if __name__ == "__main__":
+ converter = CurrencyConv()
+ print(converter.convert(100.0, "SGD", "USD"))
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage