当前位置: 代码迷 >> JavaScript >> 如何判断“ 123@231.23”是否不是JavaScript中的数字?
  详细解决方案

如何判断“ 123@231.23”是否不是JavaScript中的数字?

热度:22   发布时间:2023-06-05 09:22:40.0

parseInt("123@231.23")返回123,它是一个数字。

有大量的函数可以检测某个东西是否是数字,但是它们都依赖于parseInt

不使用正则表达式来检测它不是整数的另一种通用方法是什么?

if (isNaN("123@231.23"))
{
 alert("IsNaN - not a number");
}
else
{
 alert ("it is a number");
}

我假设OP需要区分输入是否为数字。 如果输入为float或integer,则与他的问题无关。 也许我错了...

编辑:好的,为了让大家开心,javasript中的整数非常大。 javascript中有多大的整数在检查。

问某物是否为整数就问它是9007199254740992和-9007199254740992之间的整数。 您可以使用模数%来检查数字的完整性

 $("#cmd").click(function (e) { ChectIfInteger( $("#txt").val() ) }); function ChectIfInteger(myval){ if (isNaN(myval)){ alert("not integer (not number)") } else{ //it is a number but it is integer? if( myval % 1 == 0 ){ if (myval <= 9007199254740992 && myval >= -9007199254740992) { alert("it is integer in javascript"); } else{ alert ("not integer"); } } else{ alert("nope, not integer"); } } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="txt"/> <input type="button" id="cmd" value="test input"> 

转换回String并进行比较:

String(parseInt("123"))=="123" // true
String(parseInt("123.sdfs"))=="123.sdfs" //false

如果您确实要检查“有效整数” ,则必须将isNaN与其他类似的内容结合使用:

function isValidInteger(numberToTest) {
  return !(isNaN(numberToTest) || String(parseInt(numberToTest)) !== numberToTest.toString());    
}

评估结果如下:

console.log(isValidInteger('123@231.23')); // false
console.log(isValidInteger('123231.23')); // false
console.log(isValidInteger('12323')); // true
console.log(isValidInteger(1e-1)); // false
console.log(isValidInteger('1e-1')); // false

而且即使有数字也可以使用。 要测试的 。

我认为这是测试整数的最佳方法:

function isInt(str) {
    if (typeof str !== 'number' && typeof str !== 'string') {
        return false;
    }

    return str % 1 === 0;
}

只需注意字符串/数字(如“ 123.0”)的计算结果为true

这是又一个不依赖字符串的东西:

function looksLikeInteger(n) {
  return +n == n && +n === ~~n;
}

可能应该称为“ looksLikeJavaScriptInteger”,因为它仅适用于32位整数。 它用一元+强制转换为数字,然后检查是否相等(因此,丑陋的字符串和对象被丢到那里),然后检查以确保在强制转换为整数时数值不会改变。

  相关解决方案