The Javascript regular expression is used to add a thousand-bit separator for a number and a thousand-bit javascript
Recently, I saw an interview (written test) question about how to use JavaScript to implement thousands of Separators of numbers. So I wrote a method to implement it using "Regular Expression + replace:
Copy codeThe Code is as follows:
Var thousandBitSeparator = function (numStr ){
Var B =/([-+]? \ D {3 })(? = \ D)/g;
Return numStr. replace (B, function ($0, $1 ){
Return $1 + ',';
});
}
Supports positive and negative matching and decimal point differentiation. If there is an error, we hope to point it out:-D
Attach the implementation method of another user
Copy codeThe Code is 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 to:" + Math. round (num) + ", two valid numbers:" + num. toFixed (2) + ", add the thousands separator:" + formatNumber (num ));
</Script>
The above is all the content of this article. I hope you will like it.