Skip to content

Instantly share code, notes, and snippets.

@zhang6464
Last active August 29, 2015 14:11
Show Gist options
  • Save zhang6464/1b772126bcd2a52891ae to your computer and use it in GitHub Desktop.
Save zhang6464/1b772126bcd2a52891ae to your computer and use it in GitHub Desktop.
number_format for javascript
function number_format(num, precision, glue){
num = parseFloat(num);
if(isNaN(num))
num = 0;
precision = (!precision || isNaN(precision = parseInt(precision))) ? 2 : precision;
num = num.toFixed(precision);
glue = glue ? glue : ",";
num = num.replace(/^(\d+)\.?/, function(match, p1){
var len = p1.length;
var i=len-4;// 初始位置
var trim = (match.length === len);
for(;i > -1;i -= 3){
p1 = p1.substr(0, i+1) + glue + p1.substr(i+1);
}
return p1 + (trim ? "" : ".");
});
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment