js-处理千分符

 
<html>  
 <head>  
  <title> JS千分位处理 </title>  
 </head>  
 <script>  
function $$(id){return document.getElementById(id);}  
  
/**  
 * 数字格式转换成千分位  
 *@param{Object}num  
 */  
function commafy(num) {   
//1.先去除空格,判断是否空值和非数   
num = num + "";   
num = num.replace(/[ ]/g, ""); //去除空格  
    if (num == "") {   
    return;   
    }   
    if (isNaN(num)){  
    return;   
    }   
    //2.针对是否有小数点,分情况处理   
    var index = num.indexOf(".");   
    if (index==-1) {//无小数点   
      var reg = /(-?\d+)(\d{3})/;   
        while (reg.test(num)) {   
        num = num.replace(reg, "$1,$2");   
        }   
    } else {   
        var intPart = num.substring(0, index);   
        var pointPart = num.substring(index + 1, num.length);   
        var reg = /(-?\d+)(\d{3})/;   
        while (reg.test(intPart)) {   
        intPart = intPart.replace(reg, "$1,$2");   
        }   
       num = intPart +"."+ pointPart;   
    }   
return num;   
}   
  
/**  
 * 去除千分位  
 *@param{Object}num  
 */  
function delcommafy(num){  
   num = num.replace(/[ ]/g, "");//去除空格  
   num=num.replace(/,/gi,'');  
   return num;  
}  
  
function doit(val){  
  if(val.indexOf(",")>-1){  
    $$("tx").value=delcommafy(val);  
  }else{  
    $$("tx").value=commafy(val);  
  }  
}  
  
 </script>  
 <body>  
    
  <input type="text" name="tx" id="tx" onclick="doit(this.value)" value="1234567"  />   
  
 </body>  
</html>

 

posted @ 2015-07-24 11:04  243573295  阅读(1210)  评论(0编辑  收藏  举报