转自:http://www.lanrentuku.com/js/form-31.html
<script>
function cc(s){/* if(/[^0-9\.]/.test(s)) return 0;*/
s=s.replace(/^(\d*)$/,"$1.");
s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");
s=s.replace(".",",");
var re=/(\d)(\d{3},)/;
while(re.test(s))
s=s.replace(re,"$1,$2");
s=s.replace(/,(\d\d)$/,".$1");
return s.replace(/^\./,"0.")
}
</script>
<input type="text" name="amount" οnchange="this.value=cc(this.value)">
以上代码可以为INPUT中的输入数字每隔3位加上逗号。
在做的一个银行项目中,他们的录入习惯是不加小数点,这样需要代码自动加上小数点和逗号,以前用过正则表达式,时间长差不多都忘了。上面的源码如果用正则表达式可以实现加小数点和逗号的功能,但是着急实现,所以只能用字符串操作来实现了,修改后的代码如下:
<script>
function cc(s){
/* if(/[^0-9\.]/.test(s)) return 0;*/
decimal=s.substr(s.length-2);
s=Math.floor(s/100).toString();
s=s.replace(/^(\d*)$/,"$1.");
s=s.replace(/(\d*\.\d\d)\d*/,"$1");
s=s.replace(".",",");
var re=/(\d)(\d{3},)/;
while(re.test(s))
s=s.replace(re,"$1,$2");
s=s.replace(/,(\d\d)$/,".$1");
s=s.replace(/^\./,"0.");
return s.substr(0,s.length-1)+"."+decimal;
}
}
</script>
<input type="text" name="amount" οnchange="this.value=cc(this.value)">