Recently on the Internet to see the use of JS to achieve the number of thousands of separators interview (written) question, so I wrote a "regular +replace" to achieve the method:
Copy Code code as follows:
var thousandbitseparator = function (numstr) {
var b =/([-+]?\d{3}) (? =\d)/g;
Return Numstr.replace (b, function ($, $) {
Return to + ', ';
});
}
Support sign matching, decimal point distinction, if there are errors, hope that the big points:-D
Attach an implementation method of other netizens
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
function FormatNumber (num) {
if (!/^ (\+|-)? ( \d+) (\.\d+)? $/.test (num)) {
return num;
}
var a = Regexp.$1,b = Regexp.$2,c = regexp.$3;
var re = new RegExp (). Compile ("(\\d) (\\d{3}) (, |$)");
while (Re.test (b)) {
b = B.replace (Re, "$1,$2$3");
}
Return a + "" + B + "" + C;
}
var Num=1234567/3;
Alert ("num=" +num+, Rounded: "+math.round (num) +", two-digit valid number: "+num.tofixed (2) +", add thousand Separator: "+formatnumber (num));
</script>
The above is the entire content of this article, I hope you can enjoy.