Javascript Intl.NumberFormat formatToParts()

Introduction

The Javascript Intl.Numberformat formatToParts() method does locale-aware formatting.

Intl.NumberFormat.prototype.formatToParts(number)
Parameter Optional Meaning
numberOptional A Number or BigInt to format.

It returns an Array of objects containing the formatted number in parts.

The structure the formatToParts() method returns, looks like this:

[
  { type: "integer", value: "3" }
  { type: "group", value: "." }
  { type: "integer", value: "500" }
]

Possible types are the following:

TypeMeaning
currency The currency string, such as the symbols "$" and "Dollar", "Euro" .
decimalThe decimal separator string (".").
fraction The fraction number.
group The group separator string (",").
infinity The Infinity string (" ").
integer The integer number.
literal Any literal strings or whitespace in the formatted number.
minusSignThe minus sign string ("-").
nan The NaN string ("NaN").
plusSignThe plus sign string ("+").
percentSign The percent sign string ("%").

The formatToParts() method returns locale-aware formatting in parts:


var number = 1234;

var formatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR'
});/*from   ww  w.j a va2s  .  c o  m*/

let a = formatter.formatToParts(number);
console.log(a);

The returned value can be formatted and concatenated again in a customized way.

var number = 1234;

var formatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR'
});//from   w w  w  .  ja  va  2s  . c  o m


var numberString = formatter.formatToParts(number).map(({type, value}) => {
  switch (type) {
    case 'currency': return `<u>${value}</u>`;
    default : return value;
  }
}).reduce((string, part) => string + part);

console.log(numberString);



PreviousNext

Related