1

I have a question about decimal numbers. I need to convert my numbers to decimal but I couldn't get what I exactly want.

The numbers that I used on my project.

What I want is:

  • I want to convert 130000 to 130,000 and 20911.56 to 20,911,56 (etc.)

  • First of all I searched in here and found some solutions to change my numbers :

          function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
              var numbers = string.toString().match(/\d+/g).join([]);
              numbers = numbers.padStart(decimals+1, "0");
              var splitNumbers = numbers.split("").reverse();
              var mask = '';
              splitNumbers.forEach(function(d,i){
                  if (i == decimals) { mask = decimal + mask; }
                  if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
                  mask = d + mask;
              });
              return pre + mask + pos;
          }
          var element = document.getElementById("format");
    
           var money= number_format("130000",2,',','.');
          element.innerHTML = money;
    

This code above gave me 20.911,56 but it didn't give me 130,000. Instead it is 1,300,00.What should I do? Can't I have them on the same time?

Reporter
  • 3,776
  • 5
  • 31
  • 46
  • The answer on this works for both of your cases: https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – ahsan Sep 09 '21 at 08:36
  • Does this answer your question? [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Reporter Sep 09 '21 at 08:39

1 Answers1

1

Just use Intl.NumberFormat as follows:

const formatter = new Intl.NumberFormat('en');

console.log(formatter.format(130000)); // 130,000
console.log(formatter.format(20911.56)); // 20,911.56
Robby Cornelissen
  • 81,630
  • 19
  • 117
  • 142