Parzh from Ukraine
Parzh from Ukraine

Reputation: 9873

Multiple locales in Intl.NumberFormat?

I have to deal with three different currencies: USD, UAH and EUR. To properly show each of them using Intl.NumberFormat I have to use different locale for each:

const _ = { style: "currency" };

// notice different locales
new Intl.NumberFormat("en", { ..._, currency: "USD" }).format(15); // $15.00
new Intl.NumberFormat("uk", { ..._, currency: "UAH" }).format(15); // 15,00 грн.
new Intl.NumberFormat("de", { ..._, currency: "EUR" }).format(15); // 15,00 €

So in order for this to work I have to bring a distinct locale for each currency:

const currency = {
    code: "USD", // "USD" | "UAH" | "EUR"
    rate: 1, // arbitrary
    locale: "en", // "en" | "uk" | "de"
}

new Intl.NumberFormat(currency.locale, { ..._, currency: currency.code }).format(15);

I find this approach as inelegant: model should know nothing about view.
But is there a better one?

Perhaps one could use multiple locales, like this:

const LOCALES = ["en", "uk", "de"];

// ...

new Intl.NumberFormat(LOCALES, { ..._, currency: currency.code }).format(15);

Upvotes: 2

Views: 1648

Answers (1)

Mihai Nita
Mihai Nita

Reputation: 5787

I am kind of suspicious about the need to really do that (multiple locales).

Think about the users who will see this.

They are used to see see things in one locale, and probably not know what the "locale convention" is for a certain currency.

But the thing is, the currency does not determine the formatting. If I am American, then I expect to see $12,345.67 and €12,345.67 and ¥12,345.67 I am not familiar with the European or Japanese conventions.

So I think that you should use the same locale (the current user locale) for all the formatting. Heck, I might not even know what "грн" and I would rather expect something like "12,345.67 Ukrainian Hryvnia" or "UAH 12,345.67", like most currency exchange kiosks. So it depends on the use case.

But if you definitely positively sure you want the format to follow the currency, not the user custom, then having different formatters is the only way. What you want is not a common use case, so there is no API to support that.

Upvotes: 4

Related Questions