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!

Top comments (0)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another “Coder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.