0

I currently doing formatting of number to currency but is not working on a collection of an array. I used javascript to use the Math.round function. I would like to know how properly use this function. I appreciate your suggestion. Thank you.

Array:

{
    "data": [
        [
           "9812355000",
            "23397000",
            "13976000"
        ]
    ]
}

for (var x = 0; x < data.data.length; x++) {
    for (var i0 = 0; i0 < data.data[x].length; i0++) {
        dynamicColumn += `<td>${data.data[x][i0] === null || data.data[x][i0] === "" 
                        ? 0 
                        : Math.round(data.data[x][i0])}</td>`;
   }
}

Need to achieve:

9,812,355,000
23,397,000
13,976,000
Mengo
  • 1,177
  • 1
  • 10
  • 25
  • 1
    Possible duplicate of [How to print a number with commas as thousands separators in JavaScript](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Shadow Mar 15 '17 at 04:48

3 Answers3

0
var thousandSeparationRegexp = /\B(?=(\d{3})+(?!\d))/g;

// iterate through numbers
var numberString = number.toString();
var formatted = numberString.replace(thousandSeparationRegexp, ',');

Or inline:

var formatted = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
0

To achieve the output you specified using your array, you can iterate though the digits backwards (meaning, starting from the last number and moving to the first number) and then inserting a comma after 3 digits. Some sample code could look like this:

for(let i = numberString.length - 1; i >= 0; i--) {
   if (i % 3 === 0)
      array.insert(i, ','); // this is not a real function. I leave it up to you to implement this. first param is index and second is what to insert
}
Gab
  • 1,007
  • 9
  • 22
0

You can use an Intl.NumberFormat().format(x):

function myFunction() {
  var x = document.getElementById("value_unformated").value
  var a = Intl.NumberFormat().format(x)
  var text = "Currency format: " + a + "<br>";
  document.getElementById("value_formated").innerHTML = text;
}
<input type="number" id="value_unformated" value="13528468">
<button onclick="myFunction()">Format</button>
<p id="value_formated"></p>
BioGenX
  • 402
  • 3
  • 11