如何判断&;123@231.23&;在javascript中不是一个数字

How to tell if "123@231.23" is not a number in javascript?

本文关键字:数字 一个 何判断 判断 123@231 javascript      更新时间:2023-09-26

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

有很多函数用来检测某个东西是否已经是一个数字,但是它们都依赖于parseInt。

在不使用正则表达式的情况下,检测这不是整数的另一种通用方法是什么?

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

我假设OP需要区分输入是否是数字。如果输入是浮点数或整数看起来与他的问题无关。也许,我错了…

编辑:好的,为了让大家开心,javascript中的整数非常大。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(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

这对数字也适用。以下是PLNKR测试

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

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位整数。它使用一元+强制转换为数字,然后检查是否相等(因此丑陋的字符串和对象会被抛出),然后检查以确保强制转换为整数时数字值不会改变。

相关文章: