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.
Top comments (3)
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...
Thanks, I didn't know this native function.
I always wondered if there was a way to do this sort of formatting without needing to do array splitting and groupings. Nice!