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


Java script provides a Number.isSafeInteger() to check whether the given number is a safe integer or not. If the integer is safe then returns true otherwise it will return false..

JavaScript has some restrictions regarding the number, any number should be in an SCNF standardized computer network format. If a number breaches the rule, then it is not a safe integer.

The reason behind that the number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integer b/w −(2^53-1) and (2^53-1)

Example 1

In the following example, we check the two number whether it is safe or not. Number1 is out of range i.e. is not safe the output evaluation is false.The number2 is in range i.e is safe the output evaluation is true.

<!DOCTYPE html>
<html>
<body>
   <script>
      const number1 = Number.isSafeInteger(-Math.pow(2,53)-3);
      document.write(number1 + "<br>");

      const number2 = Number.isSafeInteger(-253);
      document.write(number2);
   </script>
</body>
</html>

Example 2

In the following example, we are passing an array of integers and checking whether the given element is safe or not.

<!DOCTYPE html>
<html>
<body>
   <script>
      const arr = [15, 20, 30, 40, -100, -500];
      document.write("{");
      for (let index = 0; index < arr.length; index++) {
         document.write(Number.isSafeInteger(arr[index]) + " ");
      }
      document.write("}");
   </script>
</body>
</html>

Example 3

In the following example, data type float is not supported if you pass float value as an argument then evaluation is false. isSafeInteger() method only supports the Integer value in their range otherwise it gives false.

<html>
<body>
   <script>
      const number1 = Number.isSafeInteger(-0.567);
      document.write(number1 + " ");

      const number2 = Number.isSafeInteger(-253.0345);
      document.write(" " + number2 + " ");

      const number3 = Number.isSafeInteger(5.583);
      document.write(" " + number3);

      const number4 = Number.isSafeInteger(0 / 0);
      document.write(" " + number4 + " ");

      const number5 = Number.isSafeInteger(6 - 2);
      document.write(" " + number5 + " ");

      const number6 = Number.isSafeInteger(0);
      document.write(" " + number6);
   </script>
</body>
</html>

Updated on: 06-Dec-2022

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements