What is the maximum value for javascript number?

Asked

Viewed 434 times

4

In PHP, we have a limit to the values of the type int, which is demonstrated by the constant PHP_INT_MAX.

echo PHP_INT_MAX; // Imprime: 9223372036854775807

What about javascript? How do I find the maximum accepted value for an object Number (whole)?

3 answers

10


In the JS this representation happens like this:

Number.MAX_VALUE 

And its value is approximately 1.79E+308. That is, 179 followed by 306 digits.

See the code:

document.getElementById("demo").innerHTML = Number.MAX_VALUE;
<p id="demo"></p>

Source: Number.MAX_VALUE - Javascript | MDN

  • I don’t remember you answering a question of mine before :). thanks!

6

In ES6 there is a constant to check the largest safe integer Number.MAX_SAFE_INTEGER, you can also check the maximum amount allowed using Number.MAX_VALUE , but it is worth remembering that it is interesting that you do not use unsafe values.

If you run the Snippet below in a browser that supports this ES6 property, you will see the highest/lowest secure value.

var minNumber = document.createElement("div");
var maxNumber = document.createElement("div");
var minSafeNumber = document.createElement("div");
var maxSafeNumber = document.createElement("div");

minNumber.innerHTML = "Number.MIN_VALUE: " + Number.MIN_VALUE;
minSafeNumber.innerHTML = "Number.MIN_SAFE_INTEGER: " + Number.MIN_SAFE_INTEGER;
maxSafeNumber.innerHTML = "Number.MAX_SAFE_INTEGER: " + Number.MAX_SAFE_INTEGER;
maxNumber.innerHTML = "Number.MAX_VALUE: " + Number.MAX_VALUE;

document.body.appendChild(minNumber);
document.body.appendChild(minSafeNumber);
document.body.appendChild(maxSafeNumber);
document.body.appendChild(maxNumber);

5

Note the fact that there are two "maximum" numbers. One is the largest number of floating points, which the other answers pointed out correctly (Number.MAX_VALUE, 1.79E+308).

The other is the largest number whole which can be represented unambiguously, which is a 16-digit value (Number.MAX_SAFE_INTEGER or 2 to 53a power minus 1). This level is important for programs that need to do accurate accounts, such as financial systems.

Above this plateau, adding small values to a large number no longer works right:

Number.MAX_SAFE_INTEGER
9007199254740991
Number.MAX_SAFE_INTEGER + 2
9007199254740992
Number.MAX_SAFE_INTEGER + 3
9007199254740994
Number.MAX_SAFE_INTEGER + 4
9007199254740996
Number.MAX_SAFE_INTEGER + 5
9007199254740996

Another way to understand this problem is: in floating point, the precision is only maintained in a sum if the two numbers summed have a magnitude difference no greater than 15 digits.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.