在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 isNumeric(v) {
         return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;
   };

其他回答

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

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

我的解决方案,

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;
}

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

以下方法也可能奏效。

function isNumeric(v) {
         return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;
   };