Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Number and BigInt

Number.isSafeInteger()

Reference for Number.isSafeInteger(): testing whether a number is an integer within +/- (2^53 - 1) so arithmetic on it stays exact, with examples and pitfalls.

Number.isSafeInteger() returns true when a value is an integer that lies between Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER inclusive. Such integers are stored exactly and are not confused with their neighbours.

Use it to reject IDs, counters and sizes that have already lost precision, before you do further arithmetic on them.

JavaScript
Number.isSafeInteger(value)

Try it

JS Safe and unsafe integers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Guarding arithmetic

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Number.isSafeInteger(value)
Name Description
value The value to test. Any type is accepted.

Return value: true if value is a number, an integer, and its absolute value is at most 2 ** 53 - 1; otherwise false.

Exceptions: none.

Usage notes

  • No coercion. Strings, null and BigInt values give false.
  • Stricter than Number.isInteger(). Every safe integer is an integer, but 2 ** 53 and larger values are integers that are not safe.
  • Check results, not only inputs. An unsafe result is already rounded, so test it after the calculation, as in safeAdd above; a safe sum of two safe integers can still be unsafe.
  • Multiplication can leave the safe range quickly: Number.isSafeInteger(2 ** 30 * 2 ** 30) is false.
  • Source literals are already rounded. 9007199254740993 is parsed to 9007199254740992, so the check cannot save you from a literal you typed. Carry such values as strings or BigInt.
  • Use in validation of IDs, pagination offsets, file sizes in bytes and database counters.
  • Fractions are never safe integers, however small.

Browser support

Supported in all current browsers; it arrived with ES2015.