Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to accomplish this is by using the toLocaleString() method in JavaScript. This method can be applied to a number and will return a string with commas inserted to separate thousands. Here is an example:

let num = 1000000;
let numWithCommas = num.toLocaleString();

console.log(numWithCommas); // "1,000,000"

This approach will work for most cases and will also take into account the user's locale settings. However, if you need more control over the formatting or want to implement your own algorithm, you can write a custom function to handle the formatting. Here's an example:

function formatNumberWithCommas(num) {
  let parts = num.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
}

console.log(formatNumberWithCommas(1000000)); // "1,000,000"
console.log(formatNumberWithCommas(1234567.89)); // "1,234,567.89"

This function splits the number into two parts (before and after the decimal point), then inserts commas into the first part using a regular expression. The result is then combined with the second part and returned as a string.