用 Intl.NumberFormat.formatToParts 识别货币符号,只给该段加样式,同时保留原有的负号、分组、空白和本地化顺序。
Intl.NumberFormat 的货币结果,怎么只给货币符号加样式?
作者:闭包旅人
时间:2026-12-02
浏览:212
文章目录
做价格组件时,设计稿里可能只有货币符号是粗体,其余字符都用正常字重。如果拿 format() 的结果给第一个字符加粗,到了 -$1,234.50,变粗的就成了负号。
Intl.NumberFormat 知道每一段的用途。换成 formatToParts(),就能按类型决定哪段加样式,字符的顺序和间隔仍由格式化器决定。
先看一笔负数是怎么分段的
下面拿一笔美元负数看分段。结果按显示顺序排列,每段都有 type 和 value。留意 integer 出现了两次,因为千位分隔符把整数拆成了 1 和 234。
const amount = -1234.5;
const usd = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
currencyDisplay: 'symbol',
currencySign: 'standard',
});
for (const { type, value } of usd.formatToParts(amount)) {
console.log(type + ' ' + JSON.stringify(value));
}

en-US 下格式化 -1234.5 美元的预期分段输出。图里的 $ 对应 currency,负号有自己的 minusSign 类型。把所有 value 按顺序拼起来,结果和同一个格式化器调用 format() 一样。地区格式带的空白也会留在分段里。
只给 currency 包一层
用 DocumentFragment 先把节点拼好。碰到 currency 就建一个加粗的 span,其他片段用 append() 加成普通文本。最后用 replaceChildren() 替换内容,金额变动时再调用一次这个函数就行。
function renderCurrency(target, formatter, value) {
const fragment = document.createDocumentFragment();
for (const { type, value: text } of formatter.formatToParts(value)) {
if (type === 'currency') {
const symbol = document.createElement('span');
symbol.className = 'currency-symbol';
symbol.style.fontWeight = '700';
symbol.textContent = text;
fragment.append(symbol);
} else {
fragment.append(text);
}
}
target.replaceChildren(fragment);
}

currency 段单独带样式。最容易漏的是 literal,例如数字与货币符号之间的空白。保留它的 value,结果就会带上原来的空白字符。手动补空格,或者固定符号和数字的先后顺序,都会让页面偏离地区格式。
换个地区检查渲染结果
同样是美元,en-US 通常把符号放在前面,fr-FR 则放在金额后。下面用同一个函数做两次检查,一次比较完整文本和 format() 的结果,一次比较货币节点的数量及内容。两种地区各应输出一行 true true。

const target = document.createElement('span');
const value = 1234.5;
for (const locale of ['en-US', 'fr-FR']) {
const formatter = new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD',
currencyDisplay: 'symbol',
});
renderCurrency(target, formatter, value);
const symbols = target.querySelectorAll('.currency-symbol');
const currency = formatter.formatToParts(value)
.find(({ type }) => type === 'currency');
console.log(
target.textContent === formatter.format(value),
symbols.length === 1 && symbols[0].textContent === currency.value,
);
}实用工具推荐
电子包浆
使用 ›绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
图片压缩
使用 ›选择画质和输出格式,预览压缩前后的大小。
作者最新文章
相关文章