当前位置:Gxlcms > JavaScript > js实现数字每三位加逗号的方法

js实现数字每三位加逗号的方法

时间:2021-07-01 10:21:17 帮助过:5人阅读

本文实例讲述了js实现数字每三位加逗号的方法。分享给大家供大家参考。具体实现方法如下:

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

希望本文所述对大家的javascript程序设计有所帮助。

人气教程排行