处理字符串(向金额中每三位用逗号分开,保留两位小数)

2019-03-04  本文已影响0人  小明的明

FormatNum(str:any){

      str= ''+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"; //自动补小数点后两位

        // str = newStr;

      }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);

      }

      return str;

    }

上一篇 下一篇

猜你喜欢

热点阅读