JavaScript 格式化金額
一、使用 Intl.NumberFormat 構(gòu)造函數(shù)
這是 JavaScript 中格式化金額的最常見(jiàn)方法。Intl.NumberFormat()
構(gòu)造函數(shù)接受兩個(gè)參數(shù):語(yǔ)言環(huán)境和選項(xiàng)。語(yǔ)言環(huán)境是為其格式化金額的語(yǔ)言和地區(qū)。選項(xiàng)是一組控制金額格式的屬性。例如,可以使用樣式屬性來(lái)指定貨幣的格式,使用貨幣屬性來(lái)指定要將金額格式化為的貨幣。
const amount = 1234567.89;
const locale = "en-US";
const options = {
style: "currency",
currency: "USD",
};
const formattedAmount = new Intl.NumberFormat(locale, options).format(amount);
console.log(formattedAmount); // $1,234,567.89
二、使用 Number.prototype.toLocaleString 方法
要格式化金額,可以使用 JavaScript 的 toLocaleString()
方法。該方法可以將數(shù)字轉(zhuǎn)換為本地化的字符串表示形式,并可以指定貨幣符號(hào)、小數(shù)點(diǎn)和千位分隔符等格式。
代碼如下:
-
美元
const amount = 1234567.89; const formattedAmount = amount.toLocaleString("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formattedAmount); // $1,234,567.89
-
人民幣
const amount = 1234567.89; const formattedAmount = amount.toLocaleString("zh-CN", { style: "currency", currency: "CNY", minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formattedAmount); // ¥1,234,567.89
在這個(gè)示例中,將數(shù)字變量 amount
使用 toLocaleString()
方法轉(zhuǎn)換為本地化的字符串表示形式,并指定了以下格式:
-
style: 'currency'
表示使用貨幣格式顯示金額。 -
currency: 'USD'
表示使用美元符號(hào)作為貨幣符號(hào)。 -
minimumFractionDigits: 2
表示最少保留兩位小數(shù)。 -
maximumFractionDigits: 2
表示最多保留兩位小數(shù)。
通過(guò)這種方式,可以使用 JavaScript 快速簡(jiǎn)單地實(shí)現(xiàn)金額格式化效果。需要注意的是,toLocaleString()
方法在不同的瀏覽器和操作系統(tǒng)中可能存在差異,需要進(jìn)行兼容性測(cè)試和兼容性處理。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-459662.html
三、 使用模板字符串 + Number.prototype.toFixed + 正則替換
const amount = 1234567.89;
const formattedAmount = `¥${amount
.toFixed(2)
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
console.log(formattedAmount); // ¥1,234,567.89
在這個(gè)示例中,通過(guò) toFixed
使金額保留兩位小數(shù),使用正則替換的方式增加千位分隔符,再使用模板字符串進(jìn)行拼接。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-459662.html
到了這里,關(guān)于JavaScript 格式化金額的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!