Home > Web Front-end > JS Tutorial > js method to add commas to every three digits in numbers_javascript skills

js method to add commas to every three digits in numbers_javascript skills

WBOY
Release: 2016-05-16 16:15:31
Original
1733 people have browsed it

The example in this article describes the js method of adding commas to every three digits in numbers. Share it with everyone 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"; //自动补小数点后两位
   console.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; //逐个字符相接起来
 }
 count++;
   }
   str = newStr + (str + "00").substr((str + "00").indexOf("."),3);
   console.log(str)
 }
}

formatNum('13213.24'); //输出13,213.34
formatNum('132134.2');  //输出132,134.20
formatNum('132134');  //输出132,134.00
formatNum('132134.236');  //输出132,134.23
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template