小编典典

如何检查字符串是否为有效数字?

javascript

希望在与旧的 VB6IsNumeric()函数相同的概念空间中有一些东西?


阅读 195

收藏
2022-02-21

共1个答案

小编典典

请注意,许多基本方法都充满了细微的错误(例如空格、隐式部分解析、基数、数组强制等),这里的许多答案都没有考虑到这些错误。以下实现可能对您有用,但请注意,它不支持除小数点“ .”以外的数字分隔符:

function isNumeric(str) {
  if (typeof str != "string") return false // we only process strings!  
  return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
         !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}

要检查变量(包括字符串)是否为数字,请检查它是否不是数字:

无论变量内容是字符串还是数字,这都有效。

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

例子

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

当然,如果需要,您可以否定这一点。例如,要实现IsNumeric您给出的示例:

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

要将包含数字的字符串转换为数字:

仅当字符串包含数字字符时才有效,否则返回NaN.

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

例子

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

将字符串松散地转换为数字

用于将 ‘12px’ 转换为 12,例如:

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

例子

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

Floats

请记住,与 , 不同+numparseInt顾名思义)将通过切除小数点后的所有内容将浮点数转换为整数(如果parseInt() 由于这种行为而要使用,则最好使用另一种方法) :

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

空字符串

空字符串可能有点违反直觉。+num将空字符串或带空格的字符串转换为零,并isNaN()假设相同:

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

parseInt()不同意:

parseInt('')       // NaN
parseInt('   ')    // NaN
2022-02-21