DEV Community

Josh Kuttler
Josh Kuttler

Posted on

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.

Top comments (3)

Collapse
 
adriantoine profile image
Adrien Antoine

Nice! It's worth noting that you could use the native Intl.NumberFormat API for that as well.

developer.mozilla.org/en-US/docs/W...

Collapse
 
joshk2 profile image
Josh Kuttler

Thanks, I didn't know this native function.

Collapse
 
jhechtf profile image
Jim Burbridge

I always wondered if there was a way to do this sort of formatting without needing to do array splitting and groupings. Nice!