How to comma-separate your number in JavaScript

joshk2

Josh Kuttler

Posted on December 19, 2019

How to comma-separate your number in JavaScript

I created a simple function that does the trick with a regex expression.

The function receives either a string or a number and returns the formatted number with correct commas:

formatNumber(number) {
    number = number.toString()
    return number.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
}
Enter fullscreen mode Exit fullscreen mode

I wrote this function in TypeScript and added tests.

I've exported it to bit.dev with a live demo and docs.

Alt Text
Also, it can be easily consumed with NPM/Yarn/Bit.
https://bit.dev/joshk/jotils/format-number

If you have a better way to write this function, please write a comment.

💖 💪 🙅 🚩
joshk2
Josh Kuttler

Posted on December 19, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related