在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

当前回答

最好的方法如下:

function isThisActuallyANumber(data){
    return ( typeof data === "number" && !isNaN(data) );
}

其他回答

整数值可通过以下方式验证:

function isNumeric(value) {
    var bool = isNaN(+value));
    bool = bool || (value.indexOf('.') != -1);
    bool = bool || (value.indexOf(",") != -1);
    return !bool;
};

这种方式更容易、更快!检查所有测试!

雅虎!UI使用此项:

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

@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)。

如果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/

$('.rsval').bind('keypress', function(e){  
        var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];
        var keynum = (!window.event) ? e.which : e.keyCode; 
        var splitn = this.value.split("."); 
        var decimal = splitn.length;
        var precision = splitn[1]; 
        if(decimal == 2 && precision.length >= 2  ) { console.log(precision , 'e');   e.preventDefault(); } 
        if( keynum == 46 ){  
            if(decimal > 2) { e.preventDefault(); }  
        } 
        if ($.inArray(keynum, asciiCodeOfNumbers) == -1)
            e.preventDefault();    
  });