Last active
August 29, 2015 14:11
-
-
Save zhang6464/1b772126bcd2a52891ae to your computer and use it in GitHub Desktop.
number_format for javascript
This file contains hidden or 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
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