您的位置:首页 > Web前端 > JavaScript

js判断是否为数字, 是否为整数, 是否为浮点数

2012-04-10 21:51 211 查看
正则表达式方法 【笔者测试可用】function checkRate(input) { var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/ if (!re.test(input.rate.value)) { alert("请输入数字(例:0.02)"); input.rate.focus(); return false; } } function BASEisNotNum(theNum) { //判断是否为数字 if (BASEtrim(theNum)=="") return true; for(var i=0;i<theNum.length;i++){ oneNum=theNum.substring(i,i+1); if (oneNum<"0" || oneNum>"9") return true; } return false; } function BASEisNotInt(theInt) { //判断是否为整数 theInt=BASEtrim(theInt); if ((theInt.length>1 && theInt.substring(0,1)=="0") || BASEisNotNum(theInt)){ return true; } return false; } function BASEisNotFloat(theFloat) { //判断是否为浮点数 len=theFloat.length; dotNum=0; if (len==0) return true; for(var i=0;i<len;i++){ oneNum=theFloat.substring(i,i+1); if (oneNum==".") dotNum++; if ( ((oneNum<"0" || oneNum>"9") && oneNum!=".") || dotNum>1) return true; } if (len>1 && theFloat.substring(0,1)=="0"){ if (theFloat.substring(1,2)!=".") return true; } return false; isNaN 函数 isNaN(expression:Object) : Boolean 计算参数,如果值为 NaN(非数字),则返回 true。此函数可用于检查一个数学表达式是否成功地计算为一个数字。 可用性:Flash Player 5;ActionScript 1.0 参数 expression:Object - 要计算的布尔值、变量或其它表达式。 返回 Boolean - 一个布尔值。 例子: if(isNaN(document.login.imgcode.value)){ alert('验证码必须是数字!') document.login.imgcode.focus(); return false; } 正则表达式方法function checkRate(input){ var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/ if (!re.test(input.rate.value)) { alert("请输入数字(例:0.02)"); input.rate.focus(); return false; }}下面为普通函数写法function BASEisNotNum(theNum){//判断是否为数字if (BASEtrim(theNum)=="")return true;for(var i=0;i<theNum.length;i++){oneNum=theNum.substring(i,i+1);if (oneNum<"0" || oneNum>"9")return true;}return false;}function BASEisNotInt(theInt){//判断是否为整数theInt=BASEtrim(theInt);if ((theInt.length>1 && theInt.substring(0,1)=="0") || BASEisNotNum(theInt)){return true;}return false;}function BASEisNotFloat(theFloat){//判断是否为浮点数len=theFloat.length;dotNum=0;if (len==0)return true;for(var i=0;i<len;i++){oneNum=theFloat.substring(i,i+1);if (oneNum==".")dotNum++;if ( ((oneNum<"0" || oneNum>"9") && oneNum!=".") || dotNum>1)return true;}if (len>1 && theFloat.substring(0,1)=="0"){if (theFloat.substring(1,2)!=".")return true;}return false;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: