The Javascript regular expression is used to add a thousand-bit separator for a number and a thousand-bit javascript

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.