How to format a number with commas as thousands separators in JavaScript?

To format a number with commas as thousands separators in JavaScript, you can use the built-in toLocaleString() method or a custom implementation. Here are the best approaches:

1. Using toLocaleString() (Recommended)

The simplest and most reliable method:

const number = 1234567.89;
const formatted = number.toLocaleString('en-US');
console.log(formatted); // "1,234,567.89"

2. Custom Formatting (Regex)

For environments without Intl support or specific use cases:

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

console.log(formatNumberWithCommas(1234567)); // "1,234,567"

3. Handling Decimals

For numbers with decimal places:

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

console.log(formatNumberWithCommasAndDecimals(1234567.89)); // "1,234,567.89"

Key Notes:

  • toLocaleString() is locale-aware and handles decimals, currencies, and localization.
  • Custom regex (/\B(?=(\d{3})+(?!\d))/g) matches positions between digit groups and inserts commas.
  • For currency formatting, use:
  (1234567.89).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
  // "$1,234,567.89"

Edge Cases:

  • Works with integers: formatNumberWithCommas(1234567) → "1,234,567"
  • Handles decimals: formatNumberWithCommas(1234.56) → "1,234.56"

Use toLocaleString() for simplicity and reliability!

Leave a Reply

Your email address will not be published. Required fields are marked *