Skip to content

Instantly share code, notes, and snippets.

@lsmith
Created January 16, 2009 08:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsmith/47871 to your computer and use it in GitHub Desktop.
Save lsmith/47871 to your computer and use it in GitHub Desktop.
function format_number(n,prec,dec,sep) {
// Original by Luke Smith (http://lucassmith.name)
n = !isFinite(+n) ? 0 : +n;
prec = !isFinite(+prec) ? 2 : Math.abs(prec);
sep = sep == undefined ? ',' : sep;
var s = n.toFixed(prec),
abs = Math.abs(n).toFixed(prec),
_, i;
if (abs > 1000) {
_ = abs.split(/\D/);
i = _[0].length % 3 || 3;
_[0] = s.slice(0,i + (n < 0)) +
_[0].slice(i).replace(/(\d{3})/g, sep+'$1');
s = _.join(dec || '.');
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment