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.
Number.isSafeInteger(value)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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,
nulland BigInt values givefalse. - Stricter than
Number.isInteger(). Every safe integer is an integer, but2 ** 53and 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
safeAddabove; a safe sum of two safe integers can still be unsafe. - Multiplication can leave the safe range quickly:
Number.isSafeInteger(2 ** 30 * 2 ** 30)isfalse. - Source literals are already rounded.
9007199254740993is parsed to9007199254740992, so the check cannot save you from a literal you typed. Carry such values as strings orBigInt. - 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.