Created
June 6, 2009 02:15
-
-
Save uhop/124634 to your computer and use it in GitHub Desktop.
Fixing Spymaster's formatNumber()
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
// 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