如何使用Intl.NumberFormat实现不带货币符号的货币格式化
你没有遗漏相关配置,当前Intl.NumberFormat的标准规范中,确实没有提供在货币模式下直接隐藏货币符号的配置项。你可以使用原生的formatToParts()方法实现需求,比粗暴的字符串替换更可靠,不会误删数字中的特殊字符,也能完整保留Intl的本地化格式化能力:
const number = 123456.789; function formatCurrencyWithoutSymbol(locale, currency, value) { const formatter = new Intl.NumberFormat(locale, { style: 'currency', currency: currency }); // 拆分格式化片段,过滤掉货币符号类型的片段后重新拼接 return formatter.formatToParts(value) .filter(part => part.type !== 'currency') .map(part => part.value) .join('') .trim(); } // 测试德语区欧元格式化 console.log(formatCurrencyWithoutSymbol('de-DE', 'EUR', number)); // 输出: "123.456,79" // 测试日元格式化 console.log(formatCurrencyWithoutSymbol('ja-JP', 'JPY', number)); // 输出: "123,457"
该方案会完全遵循对应地区和货币的格式化规则,包括对应货币的小数位数控制、不同地区的千分位/小数分隔符、数字分组规则,不需要额外做适配处理。
内容的提问来源于stack exchange,提问作者Kocur4d
相关产品推荐
相关产品推荐

