Home > Web Front-end > JS Tutorial > body text

How to determine if a value is a number in javascript

青灯夜游
Release: 2023-01-05 16:11:34
Original
2351 people have browsed it

Method: 1. test() with regular expression; 2. parseFloat() function, syntax "parseFloat(value).toString()=="NaN""; 3. isNaN() function, syntax "typeof value ==='number'&&!isNaN(value)".

How to determine if a value is a number in javascript

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;
    }
}
Copy after login

Method 2: Use parseFloat() function

/**
* 验证数据 是数字:返回true;不是数字:返回false
**/
function Number(val) {
  if (parseFloat(val).toString() == "NaN") {
    
    return false;
  } else {
    return true;
  }
}
Copy after login

Method 3: Use isNaN() function

// true:数值型的,false:非数值型
  function myIsNaN(value) {
    return typeof value === 'number' && !isNaN(value);
  }
Copy after login

isNaN( )Detailed explanation

For empty arrays and arrays with only one numeric member, isNaN returns false.

isNaN([]) // false
isNaN([123]) // false
isNaN(['123']) // false
Copy after login

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);
}
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template