在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

当前回答

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

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

其他回答

function isNumeric(n) {
    var isNumber = true;

    $.each(n.replace(/ /g,'').toString(), function(i, v){
        if(v!=',' && v!='.' && v!='-'){
            if(isNaN(v)){
               isNumber = false;
               return false;
            }
         }
     });

    return isNumber;
}

isNumeric(-3,4567.89);   // true <br>

isNumeric(3,4567.89);   // true <br>

isNumeric("-3,4567.89");   // true <br>

isNumeric(3d,4567.89);   // false

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

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

我意识到这一点已经得到了多次回答,但以下是一个不错的人选,在某些情况下可能有用。

需要注意的是,它假设‘.42’不是一个数字,‘4.’不是数字,因此应该考虑到这一点。

function isDecimal(x) {
  return '' + x === '' + +x;
}

function isInteger(x) {
  return '' + x === '' + parseInt(x);
}

isDecimal通过以下测试:

function testIsNumber(f) {
  return f('-1') && f('-1.5') && f('0') && f('0.42')
    && !f('.42') && !f('99,999') && !f('0x89f')
    && !f('#abcdef') && !f('1.2.3') && !f('') && !f('blah');
}

这里的想法是,每个数字或整数都有一个“规范”字符串表示,每个非规范表示都应该被拒绝。所以我们将其转换为一个数字并返回,看看结果是否为原始字符串。

这些函数是否对您有用取决于用例。一个特点是不同的字符串表示不同的数字(如果两者都通过isNumber()测试)。

这与例如作为对象属性名称的数字相关。

var obj = {};
obj['4'] = 'canonical 4';
obj['04'] = 'alias of 4';
obj[4];  // prints 'canonical 4' to the console.

是的,内置的isNaN(对象)将比任何正则表达式解析都快得多,因为它是内置和编译的,而不是动态解释的。

尽管结果与您想要的有所不同(尝试一下):

                                              // IS NUMERIC
document.write(!isNaN('-1') + "<br />");      // true
document.write(!isNaN('-1.5') + "<br />");    // true
document.write(!isNaN('0') + "<br />");       // true
document.write(!isNaN('0.42') + "<br />");    // true
document.write(!isNaN('.42') + "<br />");     // true
document.write(!isNaN('99,999') + "<br />");  // false
document.write(!isNaN('0x89f') + "<br />");   // true
document.write(!isNaN('#abcdef') + "<br />"); // false
document.write(!isNaN('1.2.3') + "<br />");   // false
document.write(!isNaN('') + "<br />");        // true
document.write(!isNaN('blah') + "<br />");    // false

isNumeric=(el)=>{return Boolean(parseFloat(el))&&isFinite(el)}

没有什么不同,但我们可以使用布尔构造函数