revision:
The Number.isSafeInteger() static method determines whether the provided value is a number that is a safe integer.
The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that:
can be exactly represented as an IEEE-754 double precision number, and
whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation.
Number.isSafeInteger(testValue)
Parameters:
testValue : required. The value to be tested for being a safe integer.
function warn(x) { if (Number.isSafeInteger(x)) { return 'Precision safe.'; } return 'Precision may be lost!'; } console.log(warn(Math.pow(2, 53))); // Expected output: "Precision may be lost!" console.log(warn(Math.pow(2, 53) - 1)); // Expected output: "Precision safe."
<div> <p id="safe-1"></p> <p id="safe-2"></p> <p id="safe-3"></p> <p id="safe-4"></p> <p id="safe-5"></p> <p id="safe-6"></p> <p id="safe-7"></p> <p id="safe-8"></p> </div> <script> document.getElementById("safe-1").innerHTML = "Number.isSafeInteger(3) : " + Number.isSafeInteger(3); // true document.getElementById("safe-2").innerHTML = "Number.isSafeInteger(2 ** 53) : " + Number.isSafeInteger(2 ** 53); // false document.getElementById("safe-3").innerHTML = "Number.isSafeInteger(2 ** 53 - 1) : " + Number.isSafeInteger(2 ** 53 - 1); // true document.getElementById("safe-4").innerHTML = "Number.isSafeInteger(NaN) : " + Number.isSafeInteger(NaN); // false document.getElementById("safe-5").innerHTML = "Number.isSafeInteger(Infinity) : " + Number.isSafeInteger(Infinity); // false document.getElementById("safe-6").innerHTML = "Number.isSafeInteger('3') : " + Number.isSafeInteger("3"); // false document.getElementById("safe-7").innerHTML = "Number.isSafeInteger(3.1) : " + Number.isSafeInteger(3.1); // false document.getElementById("safe-8").innerHTML = "Number.isSafeInteger(3.0) : " + Number.isSafeInteger(3.0); // true </script>