DEV Community

Josh Kuttler
Josh Kuttler

Posted on

2 1

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!

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay