Number.isSafeInteger() method determines whether the provided value is a number that is a safe integer .

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

A safe integer is an integer that

  • can be exactly represented as an IEEE-754 double precision number, and
  • whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation.

例如, 2 53 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 2 53 is not a safe integer: it can be exactly represented in IEEE-754, but the integer 2 53 + 1 can't be directly represented in IEEE-754 but instead rounds to 2 53 under round-to-nearest and round-to-zero rounding. The safe integers consist of all integers from -(2 53 - 1) inclusive to 2 53 - 1 inclusive (± 9007199254740991 or ± 9,007,199,254,740,991).

Handling values larger or smaller than ~9 quadrillion with full precision requires using an arbitrary precision arithmetic library 。见 What Every Programmer Needs to Know about Floating Point Arithmetic for more information on floating point representations of numbers.

For larger integers, consider using the BigInt 类型。

句法

Number.isSafeInteger(testValue)
				

参数

testValue

The value to be tested for being a safe integer.

返回值

A 布尔 indicating whether or not the given value is a number that is a safe integer.

Polyfill

Number.isSafeInteger = Number.isSafeInteger || function (value) {
   return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};
					

范例

Using isSafeInteger

Number.isSafeInteger(3);                    // true
Number.isSafeInteger(Math.pow(2, 53));      // false
Number.isSafeInteger(Math.pow(2, 53) - 1);  // true
Number.isSafeInteger(NaN);                  // false
Number.isSafeInteger(Infinity);             // false
Number.isSafeInteger('3');                  // false
Number.isSafeInteger(3.1);                  // false
Number.isSafeInteger(3.0);                  // true
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Number.isSafeInteger' in that specification.

浏览器兼容性

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
isSafeInteger Chrome 34 Edge 12 Firefox 32 IE No Opera 21 Safari 10 WebView Android ≤37 Chrome Android 34 Firefox Android 32 Opera Android 21 Safari iOS 10 Samsung Internet Android 2.0 nodejs 0.12

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: