在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

当前回答

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

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

其他回答

这应该奏效。这里提供的一些功能有缺陷,也应该比这里的任何其他功能都快。

        function isNumeric(n)
        {
            var n2 = n;
            n = parseFloat(n);
            return (n!='NaN' && n2==n);
        }

解释:

创建自己的副本,然后将数字转换为浮点数,然后将自己与原始数字进行比较,如果它仍然是一个数字(无论是整数还是浮点数),并与原始数字匹配,也就是说,它确实是一个数。

它可以处理数字字符串和普通数字。不适用于十六进制数。

警告:使用风险自负,无保证。

它可以在没有RegExp的情况下作为

function IsNumeric(data){
    return parseFloat(data)==data;
}

从jQuery1.7开始,您可以使用jQuery.isNumeric():

$.isNumeric('-1');      // true
$.isNumeric('-1.5');    // true
$.isNumeric('0');       // true
$.isNumeric('0.42');    // true
$.isNumeric('.42');     // true
$.isNumeric('0x89f');   // true (valid hexa number)
$.isNumeric('99,999');  // false
$.isNumeric('#abcdef'); // false
$.isNumeric('1.2.3');   // false
$.isNumeric('');        // false
$.isNumeric('blah');    // false

请注意,与您所说的不同,0x89f是一个有效的数字(hex)

如果typeof n==“string”,则需要检查空/未定义条件并删除逗号(对于美国数字格式)。

function isNumeric(n)
{
    if(n === null || typeof n === 'undefined')
         return false;

    if(typeof n === 'string')
        n = n.split(',').join('');

    return !isNaN(parseFloat(n)) && isFinite(n);
}

https://jsfiddle.net/NickU/nyzeot03/3/

我意识到最初的问题没有提到jQuery,但如果您确实使用jQuery,您可以这样做:

$.isNumeric(val)

易于理解的

https://api.jquery.com/jQuery.isNumeric/(截至jQuery 1.7)