常用的JS验证和函数汇总
下面是我常用一些JS验证和函数,有一些验证我直接写到了对象的属性里面了,可以直接通过对象.方法来调用
//浮点数除法运算 functionfdiv(a,b,n){ if(n==undefined){n=2;} vart1=0,t2=0,r1,r2; try{t1=a.toString().split(".")[1].length}catch(e){} try{t2=b.toString().split(".")[1].length}catch(e){} with(Math){ r1=Number(a.toString().replace(".","")); r2=Number(b.toString().replace(".","")); return((r1/r2)*pow(10,t2-t1)).toFixed(n); } }
//浮点数乘法运算 functionfmul(a,b,n){ if(n==undefined){n=2;} varm=0,s1=a.toString(),s2=b.toString(); try{m+=s1.split(".")[1].length}catch(e){} try{m+=s2.split(".")[1].length}catch(e){} return(Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)).toFixed(n); }
//浮点数加法运算 functionfadd(a,b,n){ if(n==undefined){n=2;} varr1,r2,m; try{r1=a.toString().split(".")[1].length}catch(e){r1=0} try{r2=b.toString().split(".")[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)) return((a*m+b*m)/m).toFixed(n); }
//浮点数减法运算 functionfsub(a,b,n){ if(n==undefined){n=2;} varr1,r2,m; try{r1=a.toString().split(".")[1].length}catch(e){r1=0} try{r2=b.toString().split(".")[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)); //动态控制精度长度 //n=(r1>=r2)?r1:r2; return((a*m-b*m)/m).toFixed(n); } Number.prototype.add=function(arg){ returnfadd(this,arg); } Number.prototype.subs=function(arg){ returnfsub(this,arg); } Number.prototype.mul=function(arg){ returnfmul(this,arg); } Number.prototype.div=function(arg){ returnfdiv(this,arg); }
///格式化数字位数,不足位数默认左边补0,如果指定了参数2并且参数2的值为1则右边补0 Number.prototype.FormatLen=function(len,direct){ vard=parseInt(direct); if(isNaN(d)){d=0;} varnum=this.toString(); if(num.length<len){ for(vari=num.length;i<len;i++){ if(d==0){ num="0"+num; } else{ num+="0"; } } } returnnum; }
//格式化小数点数位,可以指定小数位数,是否四舍五入等参数 Number.prototype.FormatRadix=function(len,IsRound){ varnum=this.toString(); varnumArr=num.split('.'); varrad=0; varnumpart=parseInt(numArr[0]); if(numArr.length>=2){ if(numArr[1].length<len){ rad=parseInt(numArr[1]).FormatLen(len,1); } else{ if(numArr[1].length==len){ rad=numArr[1]; } else{ rad=numArr[1].substr(0,len); if(IsRound){ vard=parseInt(numArr[1].substr(len,1)); if(d>=5){rad+=1;if(rad.toString().length>len){numpart+=1;rad=rad.toString().substr(1,len);}} } }
} } else{ rad=rad.FormatLen(len); } returnnumpart+"."+rad; }