Last active
June 4, 2023 18:41
-
-
Save jonathanstanley/a476258ca5f8edde69eba74d77cc7d8e to your computer and use it in GitHub Desktop.
Convert between zero-decimal (integer) and decimal number for currency (for Stripe / Shopify / etc)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* https://shopify.dev/docs/api/ajax/reference/product | |
* https://stripe.com/docs/currencies#zero-decimal | |
*/ | |
function rebaseCurrency( | |
/** @type {number} */ price, | |
/** @type {string} */ isoCurrency, | |
/** @type {"toZeroDecimal" | "fromZeroDecimal"} */ transform | |
) { | |
const zeroDecimalCurrencies = [ | |
"BIF", | |
"CLP", | |
"DJF", | |
"GNF", | |
"JPY", | |
"KMF", | |
"KRW", | |
"MGA", | |
"PYG", | |
"RWF", | |
"UGX", | |
"VND", | |
"VUV", | |
"XAF", | |
"XOF", | |
"XPF", | |
// special cases; following assumed 0 decimals? | |
"ISK", | |
"HUF", | |
"TWD", | |
"UGX", | |
]; | |
const threeDecimalCurrencies = ["BHD", "JOD", "KWD", "OMR", "TND"]; | |
let base = 100; | |
if (zeroDecimalCurrencies.includes(isoCurrency)) base = 1; | |
if (threeDecimalCurrencies.includes(isoCurrency)) base = 1000; | |
return transform === "toZeroDecimal" ? price * base : price / base; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment