Skip to content

Instantly share code, notes, and snippets.

@bronzehedwick
Last active February 14, 2018 14:26
Show Gist options
  • Save bronzehedwick/bffabdb496bfc0534406 to your computer and use it in GitHub Desktop.
Save bronzehedwick/bffabdb496bfc0534406 to your computer and use it in GitHub Desktop.
Format a number with thousand's place seperating commas.
/**
* Format a number with thousand's place seperating commas.
* @param {number} num is the number to format.
* @returns {string} The formatted number.
*/
function addCommas( num ) {
var numString = num + '';
var numArray = numString.split('').reverse();
if ( numArray.length < 4 ) {
return numString;
}
for ( let i = 1, length = numArray.length; i < length; i++ ) {
if ( i % 3 === 0 ) {
numArray[i] += ',';
}
}
return numArray.reverse().join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment