# Add a thousands separator to a number using a Javascript Regular Expression

Source: Internet
Author: User

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.

Related Keywords:
Related Article

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.