Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

definition
javascript
es6
safe integer

What is a safe integer in ES6?

Educative Answers Team

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring