在项目中我们很多时候会有这样的需求输入框中限制小数点前面最多几位后面几位 如下图:
1.html里面
onkeyup="clearNoNum(this,5)"
<span class="left_common_text">融资金额</span> <input id="creditorScales_v" type="number" onkeyup="clearNoNum(this,5)" onafterpaste="this.value=this.value.replace(/[^\d.]/g,'').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')" >
2.js里面
function clearNoNum(obj, digits) { var temp = obj.value; if (temp < 0) { obj.value = ""; return; } var posDot = temp.indexOf(".");//返回指定字符在此字符串中第一次出现处的索引 if (posDot < 0) {//不包含小数点 if (temp.length <= digits) { return;//小于五位数直接返回 } else { // obj.value.delete(5, 6);//大于五位数就删掉第六位(只会保留五位) if (temp.length > digits) { obj.value = temp.substring(1, digits + 1); } return; } } var lastDot = temp.lastIndexOf("."); if (posDot != lastDot) { obj.value = ""; return; } //走到这有小数点 if (posDot > digits) { // edt.delete(5, 6);//大于五位数就删掉第六位(只会保留五位) if (temp.length > digits) { obj.value = temp.substring(1, digits + 1); } return; } if (temp.length - posDot - 1 > 2)//如果包含小数点 { // edt.delete(posDot + 3, posDot + 4);//删除小数点后的第三位 obj.value = temp.substring(0, posDot + 3); } }