What is the maximum value for Number in javascript?

4

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

echo PHP_INT_MAX; // Imprime: 9223372036854775807

And in the javascript? How do I find out the maximum accepted value for an object Number (integer)?

    
asked by anonymous 16.10.2015 / 13:45

3 answers

9

In JS this representation looks 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

    
16.10.2015 / 13:50
6

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

If you run the Snippet below on a browser that supports this ES6 property, you will see the highest / lowest security 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);
    
16.10.2015 / 13:56
5

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

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

Above this threshold, 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, precision is only kept in a sum if the two numbers added have a magnitude difference of no more than 15 digits.

    
16.10.2015 / 15:29