JS implementation thousand separators

Source: Internet
Author: User

// Regular Expressions implement thousands separators function format (num) {    var reg =/\d{1,3} (? = (\d{3}) +$)/g;     return (num + "). Replace (Reg, ' $&, ');} Console.log (Format (13123903243));  // 13,123,903,243

Explain:

The regular Expression \d{1,3} (? = (\d{3}) +$) represents a number preceded by at least one set of 3 digits.

? = indicates a forward reference, which can be used as a matching condition, but the matched content is not fetched and is the start of the next query.

The $& represents the content that matches the regular expression.

//General loop method implements thousand separatorsfunctionformat1 (num) {num= num + ';//Numeric to String    varstr = "";  for(varI=num.length-1,j=1; i>=0; I--, J + +){        if(J%3==0 && i!=0) {//every three bits plus a comma, filter exactly the first number of casesstr + = Num[i] + ', ';//add thousand decimal points comma            Continue; } STR+=Num[i]; }    returnStr.split ("). Reverse (). Join (');//String = = Array = Invert = String}console.log (FORMAT1 (13123903243));//13,123,903,243

JS implementation thousand separators

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.