How to find whether a provided number is safe integer or not in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Javascript has some limitations regarding numbers. Any number should be in a standardized computer network format. If any integer violates this rule, it can't be a safe integer. 

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). Whether to know the given number is a safe integer or not, Number.isSafeInteger() must be used. 

syntax

Number.isSafeInteger(num);

This method takes a number as a parameter and evaluates whether the number is in the range of safe integer or not. If the provided number is in the range then true will be displayed as the output else false will be displayed as the output. 

Example-1

In the following example, the provided two numbers are in the range from -(2^53 - 1) inclusive to (2^53 - 1). So the Number.isInteger() method has evaluated the numbers as true.

Live Demo

<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>

Output

true
true


Example-2

In the following example, the provided number is not in the range from -(2^53 - 1) inclusive to (2^53 - 1). So the Number.isInteger() method has evaluated the number as false.

Live Demo

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

Output

false
raja
Published on 15-Jul-2019 14:41:33
Advertisements