How to Format Numbers with Commas and Decimals in JavaScript


Sometimes, you may need to format a number value with commas and decimals in your HTML pages to make it easier to read. Here I cover how to transform a number into a comma-separated format with decimals using JavaScript. You’ll find both approaches here.

๐Ÿ“Œ Method 1: Using Intl.NumberFormat

The Intl.NumberFormat object formats numbers according to locale. Use the en-US locale (or others like en-IN, de-DE) to get thousands separators and decimal formatting:


function formatNumber(value, decimals = 2, locale = 'en-US') {
  return new Intl.NumberFormat(locale, {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals
  }).format(value);
}

// Example usage:
console.log(formatNumber(1234567.891)); // "1,234,567.89"
console.log(formatNumber(1000));        // "1,000.00"
console.log(formatNumber(1.2, 2));      // "1.20"

๐Ÿ’ก Key Points

  • Auto-formats thousands with commas and decimals.
  • You can specify any locale (e.g. 'en-IN' for Indian format).
  • Consistently adds the desired number of decimal places.

๐Ÿ” Method 2: Using toLocaleString() with toFixed()

Another simple combo:


function formatNumber2(num) {
  return Number(num.toFixed(2)).toLocaleString();
}

// Examples:
console.log(formatNumber2(1234567.891)); // "1,234,567.89"
console.log(formatNumber2(1.2));         // "1.20"

This ensures exactly two decimal places and appends commas.

๐Ÿงช Comparison

  • Intl.NumberFormat: Fully customizable with locale and exact decimal count.
  • toFixed + toLocaleString: Quick and effective for basic formatting.

✔️ Choose What Works for You

Both methods produce clean, comma‑separated numbers with decimals. For full consistency across locales and decimal control, go with Intl.NumberFormat. For a fast, reliable solution, the toFixed() + toLocaleString() combo does the job well.

For more interesting topics and hands-on guides, check out my other blog posts and keep levelling up your frontend skills!

Happy formatting! ๐ŸŽ‰

Comments

Popular posts from this blog

ReactJS : Simple way to use Echart in React

React Hooks in Modern Web Development