Trusted answers to developer questions

What is a safe integer in ES6?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

In ES6, a safe integer is an integer in the range (253,253)(-2^{53}, 2^{53}). These integers are safe because there is a one-to-one mapping between the mathematical integers and their representations in JavaScript.

Beyond this range, JavaScript integers are unsafe, which means that or more mathematical integers are represented as the same JavaScript integer. For example, starting at 2532^{53}, JavaScript can only represent every second mathematical integer.

> Math.pow(2, 53)
9007199254740992
> Math.pow(2, 53) + 1
9007199254740992
> Math.pow(2, 53) + 2
9007199254740994
> Math.pow(2, 53) + 3
9007199254740996

Formally, JavaScript documentation defines a safe integer as a number that

  • can be exactly represented as an IEEE-754 double precision number
  • the IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation.

Code

JavaScript ES6 has the built-in method Number.isSafeInteger() to check if a number is 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."

RELATED TAGS

definition
javascript
es6
safe integer
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?