NumberFormat Currency With formatToParts
Intl.NumberFormat renders currency per locale and formatToParts splits the result into typed parts, so symbol, integer, and fraction render separately.
Code
const fmt = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
console.log(fmt.format(1234.5));
console.log(fmt.format(0.5));
// formatToParts 把渲染结果拆成带类型的片段:符号与数字分开处理
const parts: Intl.DateTimeFormatPartTypes[] = [];
for (const part of fmt.formatToParts(1234.5)) {
parts.push(part.type);
console.log(part.type.padEnd(9), JSON.stringify(part.value));
}
console.log(parts.join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
$1,234.50
$0.50
currency "$"
integer "1"
group ","
integer "234"
decimal "."
fraction "50"
currency,integer,group,integer,decimal,fractionWhere the code leads
Iteration happens inside for (const part of fmt.formatToParts(1234.5)) — everything outside it runs once.
Demo state sits in top-level bindings: fmt.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
Core lines
const parts: Intl.DateTimeFormatPartTypes[] = [];
parts.push(part.type);
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Its state lives in module-level bindings: `fmt`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.