在Javascript中验证十进制数-IsNumeric()

2561

在JavaScript中,验证十进制数的最干净、最有效的方法是什么?

额外加分项:

  1. 清晰易懂。解决方案应简洁明了。
  2. 跨平台。

测试用例:

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

272
请注意,在法国,99,999是一个有效的数字,它与英式/美式格式中的99.999是相同的。因此,如果您从输入表单中读取字符串,则99,999可能是真实的。请注意,这是一条翻译,不包括任何额外的解释或内容。 - Re0sless
5
请查看这篇文章和精彩评论 - powtac
82
十进制逗号是整个欧洲和俄罗斯(英国除外)的标准。 - Calmarius
93
jQuery 1.7 引入了 jQuery.isNumeric 工具函数:http://api.jquery.com/jQuery.isNumeric/。 - Ates Goral
26
jQuery.isNumeric 无法通过 OP 的第七个测试用例 (IsNumeric('0x89f') => *false*)。然而,我不确定是否同意这个测试用例。 - Tim Lehner
显示剩余5条评论
53个回答

1

最佳方法是这样的:

function isThisActuallyANumber(data){
    return ( typeof data === "number" && !isNaN(data) );
}

0
如果您希望您的数字函数预测是隐式严格的(例如,不解析字符串),那么这应该可以解决问题。
function isNumeric(n, parse) {
    var t = typeof(n);
    if (parse){
        if (t !== 'number' && t !=='string') return false;
        return !isNaN(parseFloat(n)) && isFinite(n);
    }else{
        if (t !== 'number') return false;
        return !isNaN(n) && isFinite(n) && !_.isString(n);
    }
}

function isInteger(n, parse) {    
    return isNumeric(n, parse) && n % 1 === 0;
}

function isFloat(n, parse) {
    return isNumeric(n, parse) && n % 1 !== 0;
}

如果您想让代码解析字符串,那么只需在解析参数中传递 true。
这是对 underscore-contrib 方法的修改,它会隐式地松散解析字符串,甚至对于 isNumeric([1]) 也会返回 true,这可能会成为人们的真正陷阱。我上面的方法也会更快,因为它只在 parse = true 时调用 parseFloat()。

0

我找到了一个简单的解决方案,可能不是最好的,但它运行得很好:)

所以,我做的就是将字符串解析为整数,并检查新变量(现在是整数类型)的长度是否与原始字符串变量的长度相同。从逻辑上讲,如果两者长度相同,则意味着字符串已经完全转换为整数,而这只有在字符串仅由数字组成时才可能。

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

你可以把那段代码放进函数里,不要用 alert 而是用 return true 如果是整数。 请注意,如果字符串中使用了点号或逗号,你会发现它仍然为 false,因为你正在解析成整数。
注:在 e.val 上加上 1+,这样就不会去除起始的零。

0
使用正则表达式,我们可以覆盖问题中提到的所有情况。以下是代码: 用于整数和小数的isNumeric函数:
const isNumeric = num => /^-?[0-9]+(?:\.[0-9]+)?$/.test(num+'');

isInteger 用于判断整数:

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

0

需要检查 null/undefined 条件,并在 typeof n === 'string' 时删除逗号(针对美国数字格式)。

function isNumeric(n)
{
    if(n === null || typeof n === 'undefined')
         return false;

    if(typeof n === 'string')
        n = n.split(',').join('');

    return !isNaN(parseFloat(n)) && isFinite(n);
}

https://jsfiddle.net/NickU/nyzeot03/3/


0
关于这个问题,怎么样:
    function IsNumeric(input)
    {
        return (Number(String(input)) > -Infinity && String(input)?.length !== 0 && !(/^0x|^0b|^0o/).test(String(input)) ) ? true : false;
    }

    IsNumeric('-1') === true
    IsNumeric('-1.5') === true
    IsNumeric('0') === true
    IsNumeric('0.42') === true
    IsNumeric('.42') === true
    IsNumeric(1.1) === true
    IsNumeric(0) === true
    IsNumeric(8e5) === true
    IsNumeric('0x89f') === false // hexadecimal
    IsNumeric('0b10') === false  // binary
    IsNumeric('0o10') === false  // octal
    IsNumeric('99,999 === false
    IsNumeric('#abcdef') === false
    IsNumeric('1.2.3') === false
    IsNumeric('') === false
    IsNumeric('blah') === false
    IsNumeric(null) === false
    IsNumeric(undefined) === false
    IsNumeric(NaN) === false

-1

我使用这种方式来检查变量是否为数字:

v * 1 == v

1
问题:false * 1 == false 的结果为 true - jkdev

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

-1
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

-2

@Zoltan Lengyel在@CMS Dec的回答('09年2月5日,下午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);
    }

这个扩展了Zoltan的建议,不仅可以测试“本地化数字”如isNumber('12,50'),还可以测试“纯”数字如isNumber(2011)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接