💻 Tech
You can easily format a number based on a currency and the client’s locale using the Intl.NumberFormat
object. The Intl.NumberFormat
object is a constructor for objects that enable language-sensitive number formatting. You can use it like this:
const formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(123.45); // $123.45
It can also be used to specify the the fractional digits, which is the number of digits to use after the decimal point. Some currencies have different number of fractional digits. For example, the Japanese Yen has no fractional digits, so you can set the minimumFractionDigits
and maximumFractionDigits
to 0
:
const formatter = new Intl.NumberFormat("ja-JP", {
style: "currency",
currency: "JPY",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(123.45); // ¥123