I am using Intl.NumberFormat() to format different currency correctly.
Sadly, I have a requirement that want me to put all code at the end of the value, and not at the start.
So something like this is fine, but the code is at the start and not at the end/
const number = 123456.789;
// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency',currencyDisplay:'code', currency: 'JPY' }).format(number));
// expected output: JPY 123,457"
// I want 123,457 JPY
Is there a way to force it at the end without having to manually add it at the end by doing .replace('JYP','').trim()
I think you'll have to handle it manually. The Intl library formats the position of the code / symbol based on the given locale. Given the code is always 3 uppercase alpha characters, it should be easy to detect it.
const formatCurrency = (amount, locale, currency) => {
const fmt = new Intl.NumberFormat(locale, {
style: "currency",
currencyDisplay: "code",
currency
});
return fmt.format(amount).replace(/^([A-Z]{3})\s*(.+)$/, "$2 $1");
};
const number = 123456.789;
([
{ locale: "ja-JP", currency: "JPY" },
{ locale: "en-US", currency: "USD" },
{ locale: "fr-FR", currency: "EUR" }, // already right-aligned
]).forEach(({ locale, currency }) => {
console.log(formatCurrency(number, locale, currency));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With