如何在 JavaScript 中將數字格式化為貨幣字符串
在 JavaScript 中將數字格式化為貨幣字符串的最簡單和最流行的方法是使用 Internationalization API。它提供了對語言敏感的字符串比較、數字格式以及日期和時間格式的方法。
其中一種方法是 Intl.NumberFormat()
,這讓我們可以使用自己選擇的語言環境來格式化數字。
Intl.NumberFormat()
構造函數接受兩個參數。第一個參數是像 en-US
這樣的語言環境字符串 或 de-DE
.第二個參數是一個對象,用於指定格式化時要應用的選項:
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
console.log(formatter.format(100)) // $100.00
console.log(formatter.format(1255.786)) // $1,255.79
console.log(formatter.format(14567890)) // $14,567,890.00
在選項對像中,style
屬性用於指定格式的類型。它有以下可能的值:
decimal
用於純數字格式。currency
用於貨幣格式。unit
用於單位格式。percent
用於百分比格式。
默認style
屬性值為 decimal
.在上面的例子中,我們使用了 currency
將數字格式化為貨幣字符串。
currency
屬性允許您定義要在貨幣格式中使用的貨幣,例如 USD
, EUR
, 或 CAD
.
最後,maximumSignificantDigits
和 maximumSignificantDigits
屬性設置格式化時使用的最小和最大小數位數。
話雖如此,讓我們編寫一個通用函數,它接受一個數字值、一個可選的貨幣、區域設置、最小和最大小數位數並返回一個格式化的貨幣字符串:
const currency = (amount, currency = 'USD', locale = 'en-US', minfd = 2, maxfd = 2) => {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency,
minimumFractionDigits: minfd,
maximumFractionDigits: maxfd
}).format(amount)
}
現在我們可以使用上面的 currency()
將任意數字格式化為貨幣字符串的方法:
console.log(currency(100)) // $100.00
console.log(currency(14567890, 'CAD')) // CA$14,567,890.00
console.log(currency(1255.786, 'EUR', 'de-DE')) // 1.255,79 €