Course contentsShow
← JavaScript
Lesson 2206 of 2,72346. InternationalizationFree lesson

formatToParts() for Custom Rendering

Break formatted output into parts (integer, decimal, currency) for fine-grained control.

formatToParts() for Custom Rendering

What you'll learn: How to break down formatted numbers into labeled pieces so you can style or manipulate each part independently.


You already know that Intl.NumberFormat.format() returns a single formatted string like "$1,234.56". But what if you want to style the currency symbol in blue and the integer in bold? Or wrap the decimal part in a special <span>? You need access to the parts that make up the formatted number.

The Core Idea

The formatToParts() method returns an array of objects, each representing one piece of the formatted output. Every object has a type (like "currency", "integer", "decimal", "fraction", "group") and a value (the actual string fragment).

Think of it like disassembling a sandwich: instead of a whole sub, you get separate labeled components—bread, lettuce, cheese—so you can rearrange or style them however you want.

How It Works

const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
});

const parts = formatter.formatToParts(1234.56);
console.log(parts);
// [
//   { type: 'currency', value: '$' },
//   { type: 'integer', value: '1' },
//   { type: 'group', value: ',' },
//   { type: 'integer', value: '234' },
//   { type: 'decimal', value: '.' },
//   { type: 'fraction', value: '56' }
// ]

Now you can loop through parts, check each type, and apply custom HTML, CSS classes, or logic to specific pieces.

Custom Rendering Example

const html = parts.map(part => {
  if (part.type === 'currency') return `<span class="currency">${part.value}</span>`;
  if (part.type === 'integer') return `<strong>${part.value}</strong>`;
  return part.value;
}).join('');

console.log(html);
// <span class="currency">$</span><strong>1</strong>,<strong>234</strong>.56

Key Takeaway: formatToParts() gives you an array of labeled fragments (currency, integer, decimal, etc.), enabling fine-grained control over how each piece is rendered or styled.