Last active
February 14, 2018 14:26
-
-
Save bronzehedwick/bffabdb496bfc0534406 to your computer and use it in GitHub Desktop.
Format a number with thousand's place seperating commas.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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