在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

当前回答

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

所有整数和小数均为Numeric:

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

仅整数为isInteger:

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

其他回答

以下方法也可能奏效。

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

通过利用语言的动态类型检查,一个简单而干净的解决方案:

function IsNumeric (string) {
   if(string === ' '.repeat(string.length)){
     return false
   }
   return string - 0 === string * 1
}

如果你不在乎空格,你可以删除“如果”

参见下面的测试用例

函数IsNumeric(字符串){if(string==''.repeat(string.length)){return false}返回字符串-0===string*1}console.log('-1'+'→ ' + IsNumeric('-1'))console.log('-1.5'+'→ ' + IsNumeric('-1.5'))console.log(“0”+“→ ' + IsNumeric(“0”)console.log(“0.42”+“→ ' + IsNumeric(“0.42”)console.log('.42'+'→ ' + IsNumeric('.42'))console.log('99999'+'→ ' + IsNumeric(“99999”)console.log('0x89f'+'→ ' + IsNumeric('0x89f'))console.log('#abcdef'+'→ ' + IsNumeric(“#abcdef”)console.log('1.2.3'+'→ ' + IsNumeric('1.2.3'))console.log(“+”→ ' + IsNumeric(“”))console.log('33'+'→ ' + IsNumeric(“33”)

您可以以多种方式最小化此函数,也可以使用负值的自定义正则表达式或自定义图表来实现它:

$('.number').on('input',function(){
    var n=$(this).val().replace(/ /g,'').replace(/\D/g,'');
    if (!$.isNumeric(n))
        $(this).val(n.slice(0, -1))
    else
        $(this).val(n)
});

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

需要注意的是,它假设‘.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.