in) way in JavaScript to check if a string is a valid number?

我希望与旧的VB6 IsNumeric()函数有相同的概念空间吗?


To check if a variable (including a string) is a number, check if it is not a number:

This works regardless of whether the variable contains is a string or number.

isNaN(num)         // returns true if the variable does NOT contain a valid number

Examples

isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true

Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave:

function isNumeric(num){
  return !isNaN(num)
}

To convert a string containing a number into a number:

only works if the string only contains numeric characters, else it returns NaN .

+num               // returns the numeric value of the string, or NaN 
                   // if the string isn't purely numeric characters

Examples

+'12'              // 12
+'12.'             // 12
+'12..'            // Nan
+'.12'             // 0.12
+'..12'            // Nan
+'foo'             // NaN
+'12px'            // NaN

To convert a string loosely to a number

useful for converting '12px' to 12, for example:

parseInt(num)      // extracts a numeric value from the 
                   // start of the string, or NaN.

Examples

parseInt('12')     // 12
parseInt('aaa')    // NaN
parseInt('12px')   // 12
parseInt('foo2')   // NaN      These last two may be different
parseInt('12a5')   // 12       from what you expected to see. 

Floats

Bear in mind that, unlike +num , parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you're probably better off using another method instead):

+'12.345'          // 12.345
parseInt(12.345)   // 12
parseInt('12.345') // 12

Empty strings

Empty strings may be a little counter-intuitive. +num converts empty strings to zero, and isNaN() assumes the same:

+''                // 0
isNaN('')          // false

But parseInt() does not agree:

parseInt('')       // NaN

你可以使用RegExp方式:

var num = "987238";

if(num.match(/^-{0,1}d+$/)){
  //valid integer (positive or negative)
}else if(num.match(/^d+.d+$/)){
  //valid float
}else{
  //not valid number
}

Try the isNan function:

The isNaN() function determines whether a value is an illegal number (Not-a-Number).

This function returns true if the value equates to NaN. Otherwise it returns false.

This function is different from the Number specific Number.isNaN() method.

The global isNaN() function, converts the tested value to a Number, then tests it.

Number.isNan() does not convert the values to a Number, and will not return true for any value that is not of the type Number...

链接地址: http://www.djcxy.com/p/17456.html

上一篇: 如何测试字符串小于或等于?

下一篇: )在JavaScript中的方式来检查一个字符串是否是一个有效的数字?