Skip to content

Instantly share code, notes, and snippets.

@matthewhartman
Forked from patik/format-commas.js
Created January 13, 2021 06:36
Show Gist options
  • Save matthewhartman/6a2e2c23e7a379886a5d4e85ee2a83db to your computer and use it in GitHub Desktop.
Save matthewhartman/6a2e2c23e7a379886a5d4e85ee2a83db to your computer and use it in GitHub Desktop.
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