Skip to content

Instantly share code, notes, and snippets.

@uhop
Created June 6, 2009 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhop/124634 to your computer and use it in GitHub Desktop.
Save uhop/124634 to your computer and use it in GitHub Desktop.
Fixing Spymaster's formatNumber()
// How to format big numbers using commas to separate 1000s and abbreviations
// Example: 12345678900 => 12.34B
var numPattern = /^(\d{0,2})(\d{3})?(\d{3})?(\d{3})?(\d{3})?(\d{3})?(\d{3})?(\d{3})?(\d{3})?(\d{3})?(\d{3})?$/;
function putCommasIn(s){
return s.match(numPattern).slice(1).join(",").replace(/^\,{1,}/, "").replace(/\,{1,}$/, "");
}
function trimZeroes(s){
return s.replace(/\.?0+$/, "");
}
var exp = [0, 0, 0, 0, 3, 3, 6, 6, 6, 9, 9, 9, 12];
var abbr = "***K**M**B**T";
// logically we use floor() instead of round() to truncate a number (Spymaster-specific)
function formatNumber(n, decimals){
if(isNaN(n)){
return "";
}
if(typeof decimals != "number"){
decimals = 2;
}
if(n <= 1){
var t1 = n.toString(), t2 = n.toFixed(decimals);
return t1.length < t2.length ? t1 : t2;
}
var digits = Math.floor(Math.log(n) / Math.LN10);
if(digits >= exp.length){
digits = exp.length - 1;
}
var e = exp[digits];
var s = Math.floor(n / Math.pow(10, e - decimals)).toFixed(0);
return trimZeroes(putCommasIn(s.slice(0, -decimals)) + "." + s.slice(-decimals)) + (e && abbr.charAt(e) || "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment