Javascript Number isSafeInteger()

Introduction

The IEEE 754 number format has a distinct numerical range inside which a binary value can represent exactly one integer value.

This numerical range extends from Number.MIN_SAFE_INTEGER, or -2^53 + 1, to Number.MAX_SAFE_INTEGER, or 2^53 - 1.

Outside this range, you may attempt to store an integer, but the IEEE 754 encoding format means that this binary value may also alias to a completely different number.

To ascertain if an integer is inside this range, the Number.isSafeInteger() method allows you to easily check this:

console.log(Number.isSafeInteger(-1 * (2 ** 53)));      // false 
console.log(Number.isSafeInteger(-1 * (2 ** 53) + 1));  // true 
            //from  w w  w .  ja  v  a2s . c  om
console.log(Number.isSafeInteger(2 ** 53));             // false 
console.log(Number.isSafeInteger((2 ** 53) - 1));       // true 

The Javascript Number.isSafeInteger() method checks if the value is a safe integer.

A safe integer is an integer that

  • can be represented as an IEEE-754 double precision number
  • whose IEEE-754 representation cannot be the result of rounding any other integer
Number.isSafeInteger(testValue)
Parameter Optional Meaning
testValue Required The value to be tested.
let a = Number.isSafeInteger(3);                    // true
console.log(a);/*w  w  w .ja  v a  2  s .  com*/
a = Number.isSafeInteger(Math.pow(2, 53));      // false
console.log(a);
a = Number.isSafeInteger(Math.pow(2, 53) - 1);  // true
console.log(a);
a = Number.isSafeInteger(NaN);                  // false
console.log(a);
a = Number.isSafeInteger(Infinity);             // false
console.log(a);
a = Number.isSafeInteger('3');                  // false
console.log(a);
a = Number.isSafeInteger(3.1);                  // false
console.log(a);
a = Number.isSafeInteger(3.0);                  // true
console.log(a);



PreviousNext

Related