HTML部分代码
<input type="text" onkeyup="setnum(this)"/>
JS部分代码
<script>
function setnum(that) {
that.value = that.value.replace(/[^\d.]/g, ""); //只保留数字和点("."),其余的字符都去掉
that.value = that.value.replace(/\.{2,}/g, "."); //只保留第一个点("."),有两个点(".")只保留一个
that.value = that.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");//把点(".")进行转换防止被正则表达式抹掉
that.value = that.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//限制只能输入两位小数
if (that.value.indexOf(".") < 0 && that.value != "") {//限制首位不能是0
that.value = parseFloat(that.value);
}
}
</script>