Skip to content

Instantly share code, notes, and snippets.

@Olical
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save Olical/f4c10e58cadef60a4df8 to your computer and use it in GitHub Desktop.

Select an option

Save Olical/f4c10e58cadef60a4df8 to your computer and use it in GitHub Desktop.
/**
* Turns a number (in number or string form) into a string with commas used as
* a thousands separator.
*
* Example: 10000000 -> 10,000,000
*
* @param {String|Number} num
* @return {String}
*/
function formatNumberWithCommas(num) {
var chunks = _.chain(num.toString())
.toArray()
.reverse()
.chunk(3)
.value();
var reversed = _.map(chunks, function (n) {
return n.join('')
}).join();
return _(reversed).toArray().reverse().join('');
}
var input = [
100000000,
10000000,
1000000,
100000,
10000,
1000,
100,
10,
1,
0
];
_.map(input, formatNumberWithCommas);
/*
100,000,000
10,000,000
1,000,000
100,000
10,000
1,000
100
10
1
0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment