在 JavaScript 中格式化货币可以使用 Intl.NumberFormat
对象。
基础概念:
Intl.NumberFormat
是 JavaScript 中用于数字格式化的内置对象,可以根据指定的区域设置对数字进行格式化,包括货币格式。
优势:
类型:
currency
:指定要使用的货币符号和代码。应用场景:
示例代码:
const amount = 123456.78;
// 格式化为人民币
const formatterCN = new Intl.NumberFormat('zh-CN', {
style: 'currency',
currency: 'CNY'
});
console.log(formatterCN.format(amount)); // 输出:¥123,456.78
// 格式化为美元
const formatterUS = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
console.log(formatterUS.format(amount)); // 输出:$123,456.78
常见问题及解决方法:
minimumFractionDigits
和 maximumFractionDigits
属性来控制小数位数。例如,要控制人民币格式化为两位小数:
const formatterCN = new Intl.NumberFormat('zh-CN', {
style: 'currency',
currency: 'CNY',
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
领取专属 10元无门槛券
手把手带您无忧上云