Number formatting in JavaScript

Share Now

There are many different ways of printing an integer with a comma as a thousand separators in JavaScript.

One of the simplest ways is to use String.prototype.replace() function with the following arguments:

  • regular expression: (?=(\d{3})+(?!\d))
  • replacement value: $1,
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

console.info(formatNumber(2665)) // 2,665
console.info(formatNumber(102665)) // 102,665
console.info(formatNumber(111102665)) // 111,102,665

This will also work for decimal numbers

console.info(formatNumber(1240.5)) // 1,240.5
console.info(formatNumber(1000240.5)) // 1,000,240.5

 

Currency Formatting

This method will also work with currency formatting. Just a small modification needed.

function currencyFormat(num) {
  return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

console.info(currencyFormat(2665)) // $2,665.00

In order to format currency for a different country / locale, you would need to add some modifications to the currencyFormat method. A sample currency formatting function for DE locale:

function currencyFormatDE(num) {
  return (
    num
      .toFixed(2) // always two decimal digits
      .replace('.', ',') // replace decimal point character with ,
      .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.') + ' €'
  ) // use . as a separator
}

console.info(currencyFormatDE(1234567.89)) // output 1.234.567,89 €

Main Article: https://blog.abelotech.com/posts/number-currency-formatting-javascript/

Picture of Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert