1

I want to format a number (225121894) so its formatted as 225,121,894 I pull all the numbers from a JSON and sort and process. Here is my code

function getTestStats(jsonData)
    {
       let totalTest = 0 
       let totalCases = 0
       
       jsonData.map(covid =>
       {
           if(covid.tested !== "NA") totalTest += Number(covid.tested)
       })
       document.getElementById('covidTestStatPG').innerHTML += `${totalTest}`
            
    }

  • already answered here: https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – MVB76 Nov 06 '20 at 23:08

3 Answers3

2

Try using Number.toLocaleString(). Not only does this handle the problem of comma-separation, but it handles any type of locale-standard display settings. Below, I use en-US, but not every country/region formats commas the same, so this allows you to change as needed (i.e., to en-IN for Indian-English, etc.) without coding it up yourself everytime...

var number = 123456789;

console.log(number.toLocaleString('en-US'));
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
1

/*
 CODE FOR NUMBER FORMAT
*/
function numFormat(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

console.log( numFormat(224405) );



/*
  YOUR CODE
*/

var jsonData = [{tested:"225121894"}]; // Dummay JSON Data

function getTestStats(jsonData)
    {
       let totalTest = 0 
       let totalCases = 0
       
       jsonData.map(covid =>
       {
           if(covid.tested !== "NA") totalTest += Number(covid.tested)
       })
       
       
       document.getElementById('covidTestStatPG').innerHTML += `${numFormat(totalTest)}`
            
    }
    
    getTestStats(jsonData)
<div id="covidTestStatPG"></div>
user229044
  • 232,980
  • 40
  • 330
  • 338
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
0

You may want to check out Intl.NumberFormat.

I've used it before as follows (this is typescript but you get the idea):

const locale = "en-US";
static formatNumber(rawNumber?: number) {
  return rawNumber ? Intl.NumberFormat(locale).format(rawNumber) : "-";
}
Fabio Lopez
  • 517
  • 2
  • 5
  • 15