How to comma-separate your number in JavaScript
Josh Kuttler
Posted on December 19, 2019
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,")
}
I wrote this function in TypeScript and added tests.
I've exported it to bit.dev with a live demo and docs.
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.
💖 💪 🙅 🚩
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.