<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>小数验证</title>
<script>
String.prototype.replaceAll = function(s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2); //g全局、m多行
}
String.prototype.replaceAll2Excep = function(s1, s2) {
var temp = this;
while (temp.indexOf(s1) != -1) {
temp = temp.replace(s1, s2);
}
return temp;
}
/***
* 次验证方法很简单,但设计也很巧妙。使用的是我们常用split、array、substring等
* @author hoojo
* @param o 验证的对象,即当前文本域
* @param precision 精确多少位小数
* @version 3.1
**/
function checkFloat(o, precision) {
var val = o.value;//验证小数
if (parseFloat(val) != val) {
var ar = val.split('');
for(var i = 0; i < ar.length; i++) {
var charCode = ar[i].charCodeAt(0);
if (charCode > 57 || charCode < 46 || charCode == 47) {
//o.value = val.replaceAll(ar[i], '');这个replaeAll里面用的正则,/*+是特殊字符,所以才不能替换的
o.value = val.replaceAll2Excep(ar[i], '');
}
}
}
var ary = o.value.split('.');
if (ary.length >= 2) {
if (ary[0] == "") {
ary[0] = 0;
}
var temp = ary[1];
if (ary[1].length > precision) {
ary[1] = ary[1].substring(0, precision);
}
o.value = ary[0] + "." + ary[1];
if (0 == precision) {
o.value = ary[0];
}
} else {
var vals = o.value;
if (vals != "" && !isNaN(vals)) {
o.value = parseInt(vals);
}
}
}
</script>
</head>
<body>
<input type=text value="" onkeyup="checkFloat(this, 1)" maxlength="9"/>
</body>
</html>