Skip to content

Instantly share code, notes, and snippets.

@jonathanstanley
Last active June 4, 2023 18:41
Show Gist options
  • Save jonathanstanley/a476258ca5f8edde69eba74d77cc7d8e to your computer and use it in GitHub Desktop.
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)
/**
* 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