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


js实现数字每三位加逗号的方法,摘自:http://www.jb51.net/article/60801.htm

 

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"; //自动补小数点后两位
  }
  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;
}
formatNum( '13213.24' ); //输出13,213.24
formatNum( '132134.2' );  //输出132,134.20
formatNum( '132134' );  //输出132,134.00
formatNum( '132134.236' );  //输出132,134.23


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM