DEV Community

Dhairya Shah
Dhairya Shah

Posted on • Originally published at dhairyashah.dev

4

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!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay