如何在JavaScript中查找提供的数字是否为安全整数?

JavaScript在数字方面有一些限制。任何数字都应采用标准化的计算机网络格式。如果有任何整数违反此规则,则该整数不能为安全整数。 

安全整数由从 -(2 ^ 53-1)到(2 ^ 53-1)() 的所有整数(±9007199254740991或±9,007,199,254,740,991)组成。是否知道给定的数字是否是安全整数,必须使用Number.isSafeInteger()。 

语法

Number.isSafeInteger(num);

此方法将数字作为参数,并评估数字是否在安全整数范围内。如果提供的数字在此范围内,则将显示true作为输出,否则将显示false。 

示例1

在以下示例中,提供的两个数字的范围是从-(2 ^ 53-1)到(2 ^ 53-1)。因此Number.isInteger()方法已将数字评估为true。

<html>
<body>
<script>
   var u = Number.isSafeInteger((Math.pow(2,53))-1);
   var res = Number.isSafeInteger(-1);
   document.write(res);
   document.write("</br>");
  document.write(u);
</script>
</body>
</html>

输出结果

true
true

示例2

在以下示例中,提供的数字不在从-(2 ^ 53-1)到(2 ^ 53-1)的范围内。因此Number.isInteger()方法已将数字评估为false

<html>
<body>
   <script>
      var u = Number.isSafeInteger(-(Math.pow(2,53))-5);
      document.write(u);
   </script>
</body>
</html>

输出结果

false