固定整数位, 固定小数位(x位整数,y位小数)JavaScript 函数

    //限制整数位<=x, 小数位<=y
    var subStrQty = function (val,x , y) {
        var res = '';
        if (val.indexOf(".") != -1) {
            var arr = val.split(".");
            if (arr[1].length > y) {
                var t1 = arr[1].substring(0, y);
                var t2;
                if (arr[0].length > x) {
                    t2 = arr[0].substring(0, x);
                }
                if (t1) {
                    res = (t2 || arr[0]) + "." + (t1);
                } else {
                    res = (t2 || arr[0]) + ".";
                }
               
                //$(that).val((t2 || arr[0]) + "." + t1);
                //console.log(t2 + "." + t1)
            } else {
                res = val;
            }
        } else if (val.length > x) {
            res = val.substring(0, x);
            //$(that).val(val.substring(0, x));
        } else {
            res = val;
        }
        return res;
        
    }

使用:subStrQty (value, 12, 6);//返回最多12位整数,最多6位小数

正则 : (/^\d{1,12}\.?(\d{0,6})$/.test(value)

 
  

你可能感兴趣的:(javascript)