Skip to content

Instantly share code, notes, and snippets.

@cjwinchester
Created March 18, 2015 20:46
Show Gist options
  • Save cjwinchester/9b518d0840bbf4ef3549 to your computer and use it in GitHub Desktop.
Save cjwinchester/9b518d0840bbf4ef3549 to your computer and use it in GitHub Desktop.
A JavaScript function to return AP-formatted numbers.
function toAp(num) {
var numstripped = Number(num.toString().replace(/,|$|€|¥|£|%|(|)/g,''));
if ( isNaN(numstripped) ) {
console.log("Not a number, dude.");
}
else {
if (numstripped < 10) {
var apnums = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
return apnums[numstripped];
}
else if (numstripped > 999999) {
var striplength = Math.round(numstripped).toString().length;
if (striplength >= 7 && striplength <= 9) {
return ((numstripped / 1000000).toFixed(2) + ' million').replace('.00','')
}
else if (striplength >= 10 && striplength <= 12) {
return ((numstripped / 1000000000).toFixed(2) + ' billion').replace('.00','')
}
else if (striplength >= 13 && striplength <= 15) {
return ((numstripped / 1000000000000).toFixed(2) + ' trillion').replace('.00','')
}
else if (striplength >= 16 && striplength <= 18) {
return ((numstripped / 1000000000000000).toFixed(2) + ' quadrillion').replace('.00','')
}
}
else if (999 > numstripped <= 999999) {
numstripped += ''
, x = numstripped.split('.')
, x1 = x[0]
, x2 = x.length > 1 ? '.' + x[1] : ''
, rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
else {
return numstripped;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment