我希望在与旧的VB6 IsNumeric()函数相同的概念空间中有什么东西?


当前回答

老问题,但给出的答案中缺少几点。

科学记数法。

!isNaN('e+30')是正确的,但在大多数情况下,当人们要求数字时,他们不想匹配像1e+30这样的数字。

大浮点数的行为可能很奇怪

观察(使用Node.js):

> var s = Array(16 + 1).join('9')
undefined
> s.length
16
> s
'9999999999999999'
> !isNaN(s)
true
> Number(s)
10000000000000000
> String(Number(s)) === s
false
>

另一方面:

> var s = Array(16 + 1).join('1')
undefined
> String(Number(s)) === s
true
> var s = Array(15 + 1).join('9')
undefined
> String(Number(s)) === s
true
>

因此,如果期望String(Number(s))==s,那么最好将字符串限制在最多15位(省略前导零后)。

无穷

> typeof Infinity
'number'
> !isNaN('Infinity')
true
> isFinite('Infinity')
false
>

考虑到所有这些,检查给定字符串是否为满足以下所有条件的数字:

非科学记数法可预测地转换为数字并返回到字符串有限的

这不是一项容易的任务。下面是一个简单的版本:

  function isNonScientificNumberString(o) {
    if (!o || typeof o !== 'string') {
      // Should not be given anything but strings.
      return false;
    }
    return o.length <= 15 && o.indexOf('e+') < 0 && o.indexOf('E+') < 0 && !isNaN(o) && isFinite(o);
  }

然而,即使是这一点也远未完成。这里不处理前导零,但它们确实会破坏长度测试。

其他回答

为什么jQuery的实现不够好?

function isNumeric(a) {
    var b = a && a.toString();
    return !$.isArray(a) && b - parseFloat(b) + 1 >= 0;
};

Michael提出了类似的建议(尽管我在这里窃取了“user1691651-John”的修改版本):

function isNumeric(num){
    num = "" + num; //coerce num to be a string
    return !isNaN(num) && !isNaN(parseFloat(num));
}

以下是一个解决方案,性能很可能很差,但结果很好。这是一个由jQuery 1.12.4实现和Michael的答案组成的装置,并对前导/尾随空格进行了额外检查(因为Michael的版本对带有前导/尾随空间的数字返回true):

function isNumeric(a) {
    var str = a + "";
    var b = a && a.toString();
    return !$.isArray(a) && b - parseFloat(b) + 1 >= 0 &&
           !/^\s+|\s+$/g.test(str) &&
           !isNaN(str) && !isNaN(parseFloat(str));
};

不过,后一个版本有两个新变量。你可以通过以下方式绕过其中一个:

function isNumeric(a) {
    if ($.isArray(a)) return false;
    var b = a && a.toString();
    a = a + "";
    return b - parseFloat(b) + 1 >= 0 &&
            !/^\s+|\s+$/g.test(a) &&
            !isNaN(a) && !isNaN(parseFloat(a));
};

除了手动测试我将要遇到的几个用例之外,我还没有对这些用例进行过很多测试,这都是非常标准的东西。这是一种“站在巨人的肩膀上”的情况。

2020年10月2日:请注意,许多简单的方法都充满了微妙的错误(例如空白、隐式部分解析、基数、数组强制等),这里的许多答案都没有考虑到。以下实现可能适用于您,但请注意,它不适用于小数点“.”以外的数字分隔符:

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.

浮子

请记住,与+num不同,parseInt(顾名思义)将通过截断小数点后的所有内容来将浮点转换为整数(如果因为这种行为而希望使用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

以下内容如何?

const a = '1'

const isNumber = (a) => Number(a) === +a

我在Angular中使用了这个函数

 isNumeric(value: string): boolean {
             let valueToNumber = Number(value);
             var result = typeof valueToNumber == 'number' ;
             if(valueToNumber.toString() == 'NaN')
             {
                result = false;
             }
             return result;
          }

这个问题的公认答案有很多缺陷(正如其他几位用户所强调的)。这是用javascript实现它的最简单且经过验证的方法之一:

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

以下是一些好的测试用例:

console.log(isNumeric(12345678912345678912)); // true
console.log(isNumeric('2 '));                 // true
console.log(isNumeric('-32.2 '));             // true
console.log(isNumeric(-32.2));                // true
console.log(isNumeric(undefined));            // false

// the accepted answer fails at these tests:
console.log(isNumeric(''));                   // false
console.log(isNumeric(null));                 // false
console.log(isNumeric([]));                   // false