convert number to comma separated format javascript code example

Example 1: number with commas js

function numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

Example 2: add comma to number javascript

var n = 34523453.345
n.toLocaleString()
"34,523,453.345"

Example 3: convert number to comma separated format javascript

// Convert a number to a string with commas
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// Convert a number to a string with commas taking into account decimal point
function numberWithCommasDecimal(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

Example 4: how to format an integer with a comma in javascript

x.toString().toLocaleString(); // x must be a number