在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

当前回答

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

其他回答

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

$.isNumeric(val)

易于理解的

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

我找到了简单的解决方案,可能不是最好的,但效果很好:)

所以,我接下来要做的是,将字符串解析为Int,并检查新变量的长度大小(现在是Int类型)是否和原始字符串变量的长度相同。从逻辑上讲,如果大小相同,则意味着字符串被完全解析为int,并且只有当字符串仅由数字“构成”时,这才是可能的。

var val=1+$(e).val()+'';
var n=parseInt(val)+'';
if(val.length == n.length )alert('Is int');

您可以很容易地将该代码放在函数中,如果int,则使用return true代替alert。记住,如果您在字符串中使用点或逗号,您将检查它是否仍然为false,因为您正在解析为int。

注意:在e.val上添加1+,因此不会删除起始零。

我觉得我的代码很完美。。。

/***@param{string}s*@return{boolean}*/var isNumber=函数{return s.trim()=="" && !isNaN(数字);};

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

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

以下方法在许多情况下似乎都很有效:

function isNumeric(num) {
    return (num > 0 || num === 0 || num === '0' || num < 0) && num !== true && isFinite(num);
}

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