Format currencies for display with JavaScript
Number.toLocaleString() can format a number according to the browser locale, or a specific locale.
18.95.toLocaleString("en")
// "18.95"
18.95.toLocaleString("fr")
// "18,95"
Integer literals need to be explicitly typed:
1000.toLocaleString()
// throws an error
Number(1000).toLocaleString('ch')
// returns "1’000"
Number(1000).toLocaleString('en')
// returns "1,000"
You don’t need the number constructor when using a variable:
let n = 1000
n.toLocaleString("en")
// "1,000"
It gets interesting when you add more options:
8.95.toLocaleString("en", {
style: "currency",
currency: "CHF"
})
// "CHF 8.95"
Number(2000).toLocaleString("en", {
style: "currency",
currency: "CHF"
})
// "CHF 2,000.00"
Number(2000).toLocaleString("en", {
style: "currency",
currency: "CHF",
minimumFractionDigits: 0
})
// "CHF 2,000"