Methods for javascript to verify whether it is a number: 1. Use the isNaN() function to verify; 2. Use regular expressions to verify; 3. Use the return value of parseFloat() to verify.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to verify whether it is a number in javascript?
Method 1: Use isNaN() function
The isNaN() function is a global function that comes with js. The isNaN() function is used to check whether its parameter is a non-numeric value.
If value x is the special non-numeric value NaN (or can be converted to such a value), the returned value is true; if value x is another value, false is returned.
The disadvantage of isNaN() is that null, space and empty string will be treated as 0
NaN: Not a Number
<script> document.write(isNaN(123)); //数字 document.write(isNaN(-1.23)); //数字 document.write(isNaN(5-2)); //数字 document.write(isNaN(0)); //数字 document.write(isNaN("Hello")); //字符串 document.write(isNaN("2005/12/12")); //字符串 </script>
Output:
false false false false true true
Disadvantages: isNaN() will treat null, spaces and empty strings as 0, so the check is not rigorous.
So process it and use it with the typeof operator.
Example:
// true:数值型的,false:非数值型 function myIsNaN(value) { document.write((typeof value === 'number' && !isNaN(value))+"<br>"); } myIsNaN(10); myIsNaN(null); myIsNaN( ); myIsNaN();
Output:
true false false false
Method 2: Use regular expressions
(1), check as long as it is a number (including positive and negative Integers, 0 and positive and negative floating point numbers) will return true
/** * 校验只要是数字(包含正负整数,0以及正负浮点数)就返回true **/ function isNumber(val){ var regPos = /^[0-9]+.?[0-9]*/; //判断是否是数字。 if(regPos.test(val) ){ return true; }else{ return false; } }
(2), and verification of positive and negative numbers will return true
/** * 校验正负正数就返回true **/ function isIntNum(val){ var regPos = / ^\d+$/; // 非负整数 var regNeg = /^\-[1-9][0-9]*$/; // 负整数 if(regPos.test(val) && regNeg.test(val)){ return true; }else{ return false; } }
Method 3: Use the return value of parseFloat()
The parseFloat() function parses a string and returns a floating point number.
This function specifies whether the first character in the string is a number. If it is, the string is parsed until it reaches the end of the number, and the number is returned as a number rather than as a string.
Usage: Parse the string specified in the parameter into a floating point number and return it.
/** * 验证数据 是数字:返回true;不是数字:返回false **/ function Number(val) { if (parseFloat(val).toString() == "NaN") { return false; } else { return true; } } //isNaN(val)不能判断空串或一个空格 //如果是一个空串、空格或null,而isNaN是做为数字0进行处理的, //而parseInt与parseFloat是返回一个错误消息,这个isNaN检查不严密而导致的。
Recommended study: "javascript Advanced Tutorial"
The above is the detailed content of How to verify whether it is a number in javascript. For more information, please follow other related articles on the PHP Chinese website!