Number.isSafeInteger()

Why Number.isSafeInteger ?

The Number.isSafeInteger () method checks whether the number to be checked is a safe number. If the value to be checked is a safe number, “true” returns “false” if the number to be checked is not a safe number.

What is a safe integer?

A number which can be represented as an IEEE-754 double precision number i.e. all integers from (253 – 1) to -(253 – 1)).

The IEEE 754 standard specifies a binary64 as having:

• Sign bit: 1 bit
• Exponent: 11 bits
• Significand precision: 53 bits (52 explicitly stored)

Syntax:

Number.isSafeInteger(value)

value (required): value or number to be tested

JavaScript isSafeInteger Examples

Example 1

``````        let val1 = Number.isSafeInteger(1234);
let val2 = Number.isSafeInteger(1.55);
let val3 = Number.isSafeInteger(-8.99);
let val4 = Number.isSafeInteger(0);
let val5 = Number.isSafeInteger(null);
let val6 = Number.isSafeInteger("394");
let val7 = Number.isSafeInteger("truecodes.org");
let val8 = Number.isSafeInteger(2000 / 1000);
let val9 = Number.isSafeInteger(Infinity);
let val10 = Number.isSafeInteger(-Infinity);
let val11 = Number.isSafeInteger(0 / 0);
let val12 = Number.isSafeInteger(function () { });
let val13 = Number.isSafeInteger(2019 / 02 / 03);

console.log(val1);
console.log(val2);
console.log(val3);
console.log(val4);
console.log(val5);
console.log(val6);
console.log(val7);
console.log(val8);
console.log(val9);
console.log(val10);
console.log(val11);
console.log(val12);
console.log(val13);``````

output:

true
false
false
true
false
false
false
true
false
false
false
false
false

Example 2

``````        var result = Number.isSafeInteger(90071991);
if (result) {
console.log("Given number is a safe integer");
} else {
console.log("Given number is not a safe integer");
}``````

output:

Given number is a safe integer

Example 3

``````        var result1 = Number.isSafeInteger(45.2);
console.log(result1);

var result2 = Number.isSafeInteger(-38);
console.log(result2);

var result3 = Number.isSafeInteger(0 / 8);
console.log(result3);``````

output:

false
true
true

Polyfill

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

Source:

Browser Support

 Chrome yes Edge yes Firefox 32 Internet Explorer yes Opera 10 Safari yes Android webview yes Chrome for Android yes Edge mobile yes Firefox for Android 32 Opera Android yes

1 Comment »

This site uses Akismet to reduce spam. Learn how your comment data is processed.