在JavaScript中验证十进制数字最干净、最有效的方法是什么?

奖励积分:

清晰解决方案应干净简单。跨平台。

测试用例:

01. IsNumeric('-1')      => true
02. IsNumeric('-1.5')    => true
03. IsNumeric('0')       => true
04. IsNumeric('0.42')    => true
05. IsNumeric('.42')     => true
06. IsNumeric('99,999')  => false
07. IsNumeric('0x89f')   => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3')   => false
10. IsNumeric('')        => false
11. IsNumeric('blah')    => false

当前回答

无需使用额外的库。

const IsNumeric = (...numbers) => {
  return numbers.reduce((pre, cur) => pre && !!(cur === 0 || +cur), true);
};

Test

> IsNumeric(1)
true
> IsNumeric(1,2,3)
true
> IsNumeric(1,2,3,0)
true
> IsNumeric(1,2,3,0,'')
false
> IsNumeric(1,2,3,0,'2')
true
> IsNumeric(1,2,3,0,'200')
true
> IsNumeric(1,2,3,0,'-200')
true
> IsNumeric(1,2,3,0,'-200','.32')
true

其他回答

要添加的几个测试:

IsNumeric('01.05') => false
IsNumeric('1.') => false
IsNumeric('.') => false

我想到了这个:

function IsNumeric(input) {
    return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(input);
}

解决方案包括:

开头的可选负号一个零,或者一个或多个不以0开头的数字,或者只要后面有一个周期,就不加任何数字后跟一个或多个数字的句点

对我来说,这是最好的方式:

isNumber : function(v){
   return typeof v === 'number' && isFinite(v);
}

通过利用语言的动态类型检查,一个简单而干净的解决方案:

function IsNumeric (string) {
   if(string === ' '.repeat(string.length)){
     return false
   }
   return string - 0 === string * 1
}

如果你不在乎空格,你可以删除“如果”

参见下面的测试用例

函数IsNumeric(字符串){if(string==''.repeat(string.length)){return false}返回字符串-0===string*1}console.log('-1'+'→ ' + IsNumeric('-1'))console.log('-1.5'+'→ ' + IsNumeric('-1.5'))console.log(“0”+“→ ' + IsNumeric(“0”)console.log(“0.42”+“→ ' + IsNumeric(“0.42”)console.log('.42'+'→ ' + IsNumeric('.42'))console.log('99999'+'→ ' + IsNumeric(“99999”)console.log('0x89f'+'→ ' + IsNumeric('0x89f'))console.log('#abcdef'+'→ ' + IsNumeric(“#abcdef”)console.log('1.2.3'+'→ ' + IsNumeric('1.2.3'))console.log(“+”→ ' + IsNumeric(“”))console.log('33'+'→ ' + IsNumeric(“33”)

@CMS的回答:您的代码段在我的机器上使用nodejs处理空白情况时失败。所以我把它和@joel对以下问题的回答:

is_float = function(v) {
    return !isNaN(v) && isFinite(v) &&
        (typeof(v) == 'number' || v.replace(/^\s+|\s+$/g, '').length > 0);
}

我用那些浮动的案例对其进行了统一测试:

var t = [
        0,
        1.2123,
        '0',
        '2123.4',
        -1,
        '-1',
        -123.423,
        '-123.432',
        07,
        0xad,
        '07',
        '0xad'
    ];

以及那些没有浮点数的情况(包括空白空格和对象/数组):

    var t = [
        'hallo',
        [],
        {},
        'jklsd0',
        '',
        "\t",
        "\n",
        ' '
    ];

这里的一切都按预期进行。也许这有帮助。

这里可以找到完整的源代码。

如果我没有弄错,这应该匹配任何有效的JavaScript数值,不包括常量(Infinity,NaN)和符号运算符+/-(因为就我而言,它们实际上不是数字的一部分,它们是独立的运算符):

我需要一个令牌化器,将数字发送到JavaScript进行评估不是一个选项。。。它肯定不是最短的正则表达式,但我相信它抓住了JavaScript数字语法的所有细微之处。

/^(?:(?:(?:[1-9]\d*|\d)\.\d*|(?:[1-9]\d*|\d)?\.\d+|(?:[1-9]\d*|\d)) 
(?:[e]\d+)?|0[0-7]+|0x[0-9a-f]+)$/i

有效数字包括:

 - 0
 - 00
 - 01
 - 10
 - 0e1
 - 0e01
 - .0
 - 0.
 - .0e1
 - 0.e1
 - 0.e00
 - 0xf
 - 0Xf

无效数字将为

 - 00e1
 - 01e1
 - 00.0
 - 00x0
 - .
 - .e0