在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

当前回答

@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",
        ' '
    ];

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

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

其他回答

这里有一个稍微改进的版本(可能是最快的版本),我用它代替了jQuery的变体,我真的不知道他们为什么不使用这个:

function isNumeric(val) {
    return !isNaN(+val) && isFinite(val);
}

jQuery版本的缺点是,如果您传递一个带前导数字和尾随字母(如“123abc”)的字符串,parseFloat|parseInt将提取数字分数并返回123,但第二个保护isFinite无论如何都会失败。使用一元+运算符,它将在第一个守卫中死亡,因为+为此类混合体抛出NaN:)虽然有点表现,但我认为语义上有了坚实的收获。

我的解决方案,

function isNumeric(input) {
    var number = /^\-{0,1}(?:[0-9]+){0,1}(?:\.[0-9]+){0,1}$/i;
    var regex = RegExp(number);
    return regex.test(input) && input.length>0;
}

它似乎在任何情况下都有效,但我可能错了。

无需使用额外的库。

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

@Zoltan Lengyel在@CMS 12月的回答(2009年2月,5:36)中对“其他地区”的评论(4月26日,2:14):

我建议测试typeof(n)==“string”:

    function isNumber(n) {
        if (typeof (n) === 'string') {
            n = n.replace(/,/, ".");
        }
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

这扩展了Zoltans的建议,使其不仅能够测试“本地化数字”,如isNumber('12,50'),还可以测试“纯”数字,如isNumber(2011)。

return (input - 0) == input && input.length > 0;

对我不起作用。当我输入警报并测试时,input.length未定义。我认为没有检查整数长度的属性。所以我做的是

var temp = '' + input;
return (input - 0) == input && temp.length > 0;

它工作得很好。