Home > Article > Web Front-end > How to determine if a value is a number in javascript
Method: 1. test() with regular expression; 2. parseFloat() function, syntax "parseFloat(value).toString()=="NaN""; 3. isNaN() function, syntax "typeof value ==='number'&&!isNaN(value)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use test() regular expression
The verification will return true as long as it is a number (including positive and negative integers, 0 and positive and negative floating point numbers)
/** * 校验只要是数字(包含正负整数,0以及正负浮点数)就返回true **/ function isNumber(val){ var regPos = /^\d+(\.\d+)?$/; //非负浮点数 var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数 if(regPos.test(val) && regNeg.test(val)){ return true; }else{ return false; } }
Method 2: Use parseFloat() function
/** * 验证数据 是数字:返回true;不是数字:返回false **/ function Number(val) { if (parseFloat(val).toString() == "NaN") { return false; } else { return true; } }
Method 3: Use isNaN() function
// true:数值型的,false:非数值型 function myIsNaN(value) { return typeof value === 'number' && !isNaN(value); }
isNaN( )Detailed explanation
For empty arrays and arrays with only one numeric member, isNaN returns false.
isNaN([]) // false isNaN([123]) // false isNaN(['123']) // false
The reason why the above code returns false is that these arrays can be converted into numerical values by the Number function. Please refer to the chapter "Data Type Conversion".
Therefore, before using isNaN, it is best to determine the data type.
function myIsNaN(value) { return typeof value === 'number' && !isNaN(value); }
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to determine if a value is a number in javascript. For more information, please follow other related articles on the PHP Chinese website!