Last active
August 29, 2015 14:20
-
-
Save jeffwesson/bc4e3f94596f197fe51d to your computer and use it in GitHub Desktop.
Format a given number with thousands delimited by commas
This file contains 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
function formatNumber(num) { | |
if (!isNaN(Number(num))) { | |
var numLength = num.toString().split('').length; | |
if (numLength % 3 !== 0) { | |
// do complex shit, | |
// but return 0 for now | |
return 0; | |
} | |
var regexString = ''; | |
var formatTemplate = ''; | |
for (var i = 1; i <= (numLength / 3); ++i) { | |
regexString += '(\\d{3})'; | |
if (i < numLength / 3) { | |
formatTemplate += '$' + i.toString() + ','; | |
} else { | |
formatTemplate += '$' + i.toString(); | |
} | |
} | |
var regex = new RegExp(regexString,'g'); | |
var formattedNumber = num.toString().replace(regex, formatTemplate); | |
console.log('regex:', regex); | |
console.log('formatTemplate:', formatTemplate); | |
return formattedNumber; | |
} else { | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment