DEV Community

Dhairya Shah
Dhairya Shah

Posted on • Originally published at


How to seperate number with commas in Javascript

When working with numbers in Javascript, you may need to format them to make them more readable. 

You can convert a number value to a comma-separated string. Here are two approaches:
using toLocaleString()
using Regex

 using toLocaleString()

The toLocalString() is a default built-in browser method of the Number object that returns the number (in string) representing the locale.

You can pass any locale inside the parantheses as a parameter.

  const number = 14500240 
  const formatedNumber = number.toLocaleString("en-IN") 
Enter fullscreen mode Exit fullscreen mode

 using Regex

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

 const number = numberWithCommas(234234.555); 
Enter fullscreen mode Exit fullscreen mode


After reading this article, you'll be able to use either of these two techniques to format numbers in Javascript:
 - using toLocaleString()
 - using Regex

Thanks for reading!

Top comments (0)


11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!