html中使用javascript脚本实现文本框中千分号的示例分享


摘要:
下文讲述js脚本实现,焦点离开文本框时,文本框中的数字采用千分号的模式显示,如下例所示:

例:

 
<meta charset='utf-8' />
<p>
 maomao365.com <br />
  文本框中千分号的示例分享
</p>
<hr />
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"
 ></script>

<input type="text" id="txtTest" /> 


<script> 
    //光标离开后触发事件
    $("#txtTest").blur(function(){
        var obj = this.value;
        var mnyReg = /^([1-9][0-9]*|(([0]\.[0-9]{0,2}[1-9]\d*|[1-9][0-9]*\.\d*)))$/;//根据需求修改
        if(!(mnyReg.test(obj))){
              this.value =0; //是否为数值类型验证
              return;
          }
        var n = 3; //保留小数位数
        obj = parseFloat(obj).toFixed(n); //数值转换为保留的小数位数
        var left = obj.split(".")[0].split("").reverse();//left = ["6","5","4","3","2","1"]
        var right = obj.split(".")[1]; //小数点后面的数值缓存
        var total = new Array(); 
        for (i = 0; i < left.length; i++) { 
            total.push(left[i]);
            if((i + 1) % 3 == 0 && (i + 1) != left.length){
                total.push(",");
            }
        } //total = ["6","5","4",",","3","2","1"]
        $("#txtTest").val(total.reverse().join("") + "." + right); 
    })

//获取焦点时 剔除逗号变成数值类型
$("#txtTest").focus(function(){
        var oldMny = this.value.replace(/,/g, '');
        if(oldMny.indexOf(".")>0){
            oldMny = oldMny.replace(/0+?$/,"");//去除尾部多余的0
            oldMny = oldMny.replace(/[.]$/,"");//如果最后一位是.则去掉
        }
        this.value = oldMny;
    })
 
//取值方法 需剔除 逗号
//var v = $("#txtTest").val().trim().replace(/,/g, '');

</script>
javascript js实现千分号的示例分享

javascript js实现千分号的示例分享