在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(num) {
    return (num > 0 || num === 0 || num === '0' || num < 0) && num !== true && isFinite(num);
}

这是建立在这个答案之上的(也是这个答案的基础):https://stackoverflow.com/a/1561597/1985601

其他回答

要添加的几个测试:

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

我想到了这个:

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

解决方案包括:

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

使用正则表达式,我们可以涵盖问题中提出的所有情况。这里是:

所有整数和小数均为Numeric:

const isNumeric = num => /^-?[0-9]+(?:\.[0-9]+)?$/.test(num+'');

仅整数为isInteger:

const isInteger = num => /^-?[0-9]+$/.test(num+'');

我使用的是更简单的解决方案:

function isNumber(num) {
    return parseFloat(num).toString() == num
}

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

雅虎!UI使用此项:

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