Add a thousands separator to a number using a Javascript Regular Expression
During the currency conversion in the project, you often need to enable automatic formatting of the entered number and automatic thousands of separators. On the Internet, I am not very satisfied with the Code implemented by other netizens, so I studied it and shared it with you.
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:
The 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
The 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.