DEV Community

Dhairya Shah
Dhairya Shah

Posted on • Originally published at dhairyashah.dev

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
Conclusion

 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") 
  console.log(formatedNumber) 
   
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); 
 console.log(number); 
Enter fullscreen mode Exit fullscreen mode

 Conclusion

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!

Latest comments (0)