Takeshi Tokugawa YD
Takeshi Tokugawa YD

Reputation: 979

How to check if number greater than Number.MAX_SAFE_INTEGER in ECMAScript

In ECMAScript, the maximal value of number is 9007199254740991. But how to check is value greater than 9007199254740991?

// ---------------- ↓ We don't know at advance which value user will pass
function examle(parameter: number | BigInt): void {
    // check the value before do something with it
}

Below code works as expected, but I not sure that do it right.

console.log(9007199254740992 > 9007199254740991); // "true"
console.log(9007199254740993 > 9007199254740991); // "true"
console.log(9007199254740994 > 9007199254740991); // "true"

Upvotes: 1

Views: 1713

Answers (1)

Peter Mudrievskij
Peter Mudrievskij

Reputation: 308

In javascript all numbers (integers and reals) are stored using double-precision floating-point numbers. The actual maximum is Number.MAX_VALUE which is somewhere around 1.79E+308. So you are doing everything right.

See MAX_SAFE_INTEGER, MAX_VALUE and this article

Also try writing to console numbers bigger than 9007199254740991. You'll see that they are not as precise

Upvotes: 1

Related Questions