JavaScript Number.isSafeInteger()Method

Number 对象参考手册JavaScript Number Object

Example

Detect whether the parameter is a "safe integer":

Number.isSafeInteger(123); Number.isSafeInteger(-123); Number.isSafeInteger('123'); Number.isSafeInteger(5-2); Number.isSafeInteger(0); Number.isSafeInteger(0.5); Number.isSafeInteger(0/0);

Try it Yourself »

Definition and Usage

The isSafeInteger() method is used to determine whether the passed parameter value is a "safe integer". If it is a safe integer, it returns true; otherwise, it returns false.

A safe integer is an integer that meets the following conditions:

  • It can be accurately represented as an IEEE-754 double-precision number.
  • Its IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation.

For example, 2^53 - 1 is a safe integer. It can be represented exactly, and under any IEEE-754 rounding mode, no other integer rounds to this integer. In contrast, 2^53 is not a safe integer. It can be represented using IEEE-754, but 2^53 + 1 cannot be directly represented using IEEE-754; in round-to-nearest and round-toward-zero, it is rounded to 2^53.

The range of safe integers is integers between -(2^53 - 1) and 2^53 - 1, inclusive of -(2^53 - 1) and 2^53 - 1.

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

Browser Support

Number.isSafeInteger() is a new feature in ECMAScript 6 (ES6).

Basically, the latest browser versions all support ES6 (JavaScript 2015).

Number.isSafeInteger() is not supported in Internet Explorer 11 and earlier browser versions.

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

Syntax

Number.isSafeInteger(value)

Parameter Values

Parameter Description
value The value to test.

Return Value

Type Description
Boolean Returns true if it is a safe integer, otherwise false.

Technical Details

JavaScript Version: ECMAScript 6

More Examples

Example

Check whether the parameter is a safe integer:

Number.isSafeInteger(Math.pow(2, 53)); Number.isSafeInteger(Math.pow(2, 53) - 1); Number.isSafeInteger(true); Number.isSafeInteger(false); Number.isSafeInteger(Infinity); Number.isSafeInteger(-Infinity);

Try it Yourself »

Number 对象参考手册JavaScript Number Object

Other Extensions