Home > Back-end >  how can i put commas in thousands?
how can i put commas in thousands?

Time:05-25

`$.ajax({
                url : "/selectList.do",
                data:{memberNo:memberNo},                   
                success : function(list){
                    console.log(list);
                    for(let i=0;i<list.length;i  ){
                             list[i].NUMBER;
                    }
                  }
            });`

I got numbers from ajax and I want to put a commas in this number in thousands.

How can I do it?

CodePudding user response:

Try use regex

const thousands = (o) => o.toString().replace(/\B(?<!\.\d*)(?=(\d{3}) (?!\d))/g, ',');

console.log(thousands(123456789));
console.log(thousands(123456789.123));

Or use Number.prototype.toLocaleString()

const num = 123456.789;

console.log(num.toLocaleString()); 

Or use Intl.NumberFormat

const number = 123456.789;
const nf = new Intl.NumberFormat('en-US');

console.log(nf.format(number));

Or use Array.prototype

const insert = (arr, index, newItem) => [
  ...arr.slice(0, index),
  newItem,
  ...arr.slice(index)
];

const thousands = (o) => {
  let tmpArr = o.toString().split('.');
  let splitArr = tmpArr[0].split('');
  const reversed = splitArr.reverse();
  for (let i = 1; i <= reversed.length; i  ) {
    if (i % 3 == 0)
      splitArr = insert(splitArr, i, ',');
  }
  tmpArr[0] = tmpArr.length > 1 ? '.' : '';
  return splitArr.reverse().concat(tmpArr).join('');
};

console.log(thousands(123456));
console.log(thousands(123456.789));

  • Related