skip to Main Content

I have the following function:

formatNumericValues() {
    const numberFormat = new Intl.NumberFormat('es', {
      minimumFractionDigits: 0,
      maximumFractionDigits: 2,
    });

    this.tableItems.forEach((item) => {
      // eslint-disable-next-line no-restricted-syntax
      for (const key in item) {
        if (typeof item[key] === 'number') {
          let formattedValue = numberFormat.format(item[key]);

          if (item[key] % 1 !== 0) { // Verifica si el número tiene decimales
            formattedValue = item[key].toFixed(2).replace(/./g, ',');
          } else {
            formattedValue = formattedValue.replace(/.00$/, '');
          }

          item[key] = formattedValue;
        }
      }
    });
  }

I want the ‘.’ to be placed starting at 1,000, but it is doing so starting at 10,000. I have tried placing the following without success:

const numberFormat = new Intl.NumberFormat('en', {
      minimumFractionDigits: 0,
      maximumFractionDigits: 2,
      minimumSignificantDigits: 1,
});

2

Answers


  1. You can use the useGrouping constructor option to always show the grouping separator. Here’s an example:

    const formatter = new Intl.NumberFormat("es-ES", { useGrouping: "always" });
    
    for (
      const n of Array.from({ length: 10 }, (_, i) => 10 ** i)
    ) console.log(formatter.format(n));
    /* Logs:
                1
               10
              100
            1.000
           10.000
          100.000
        1.000.000
       10.000.000
      100.000.000
    1.000.000.000
    */
    Login or Signup to reply.
  2. Adding to jsejcksn’s answer:

    The Spanish locale has minimumGroupingDigits = 2 (see here), which means that no "thousands grouping character" will be inserted if there would be fewer than two digits before it. Read the explanation here.

    For comparison, the German locale has minimumGroupingDigits = 1 (see here):

    console.log(
      Intl.NumberFormat("es").format(1000),
      Intl.NumberFormat("de").format(1000)
    );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search