Skip to content

Instantly share code, notes, and snippets.

@patik patik/format-commas.js
Last active Nov 7, 2016

What would you like to do?
Format number with commas
// Converts `1234567` => `"1,234,567"
// Does not support decimals yet
function formatNumberWithCommas (number) {
return ('' + number) // Convert to a string
.split('').reverse().join('') // Reverse the order of the characters (which are all digits at this point)
.replace(/(...)/g, '$1,') // Insert a comma after every three digits
.split('').reverse().join('') // Un-reverse the characters
.replace(/^,/, ''); // Remove any commas that were added to the beginning (i.e. if the number of digits was a multiple of three)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.