Skip to content

Instantly share code, notes, and snippets.

@patik
Last active June 22, 2021 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save patik/c9e8d95dd5c35ae634d418a48b70d042 to your computer and use it in GitHub Desktop.
Save patik/c9e8d95dd5c35ae634d418a48b70d042 to your computer and use it in GitHub Desktop.
Format number with commas
// Converts "1234567.89" => "1,234,567.89"
function formatNumberWithCommas(number) {
const parts = number.split('.')
return ('' + parts[0]) // 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)
.concat(parts[1] ? '.' + parts[1] : '') // Re-add the decimal, if any
}
@matthewhartman
Copy link

This is a really cool technique mate!

You can support decimal pretty easily.

function formatNumberWithCommas (number) {
  var num = number.split('.');
  return ('' + num[0])
  .split('').reverse().join('')
  .replace(/(...)/g, '$1,')
  .split('').reverse().join('')
  .replace(/^,/, '')
  .concat('.' + num[1]);
};
console.log(formatNumberWithCommas("1000000.23"));

@patik
Copy link
Author

patik commented Jun 21, 2021

Awesome, thanks! Works great, I'll add it.

image

@matthewhartman
Copy link

Oh yeah! Nice one mate!! 🤟

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment