限制输入框小数点位数 - 老马资料库

限制输入框小数点位数

类别:程序开发 时间:2024-09-06 00:07:52 点击:4240
function checkNum(obj,intNum=0,decNum=0) {
    var value=obj.value;
    var changeValue,t1,t2;
    switch (decNum){
            case 0:
                value=value.replace(/[^\d]/g,'');
                value=value.replace(/^0\d+/g,'0');
                if(intNum!=0){
                    value=value.substr(0,intNum);
                }
                break;
            default:
                value=value.replace(/[^\d.]/g,'');
                value=value.replace(/^[^\d]/g,'');
                value=value.replace(/\.{2}/g,'.');
                value=value.replace(/^0\d+/g,'0');
                changeValue=value.split('.');
                if(changeValue.length>1){
                    if(intNum==0){
                        t1=changeValue[0];
                    }else{
                        t1=changeValue[0].substr(0,intNum);
                    }
                    t2=changeValue[1].substr(0,decNum);
                    value=t1+'.'+t2;
                }else{
                    if(intNum!=0){
                        value=value.substr(0,intNum);
                    }
                }
                break;
        }
    if(obj.value!=value){
        obj.value=value;
    }
    return value;
}
<input type="number" oninput=checkNum(this,1,4)>