Javascript implements the method of adding a comma to each three digits, and JavaScript numbers are separated by three commas.

Source: Internet
Author: User

Javascript implements the method of adding a comma to each three digits, and JavaScript numbers are separated by three commas.

This example describes how to add a comma (,) to each three digits in JavaScript. Share it with you for your reference. The specific implementation method is as follows:

Function formatNum (str) {var newStr = ""; var count = 0; if (str. indexOf (". ") =-1) {for (var I = str. length-1; I> = 0; I --) {if (count % 3 = 0 & count! = 0) {newStr = str. charAt (I) + "," + newStr;} else {newStr = str. charAt (I) + newStr;} count ++;} str = newStr + ". 00 "; // automatically add two consoles after the decimal point. log (str)} else {for (var I = str. indexOf (". ")-1; I> = 0; I --) {if (count % 3 = 0 & count! = 0) {newStr = str. charAt (I) + "," + newStr;} else {newStr = str. charAt (I) + newStr; // concatenate characters one by one} count ++;} str = newStr + (str + "00 "). substr (str + "00 "). indexOf (". "), 3); console. log (str)} formatNum ('100. 13213. 24 '); // output 13,213.34 formatNum ('100. 000. 2 '); // output 132,134.20 formatNum ('20160301'); // output 132134 formatNum ('20160301. 236 '); // output 132,134.23

I hope this article will help you design javascript programs.

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.