Open In App

What is JavaScript’s highest integer value that a Number can go to without losing precision?

Last Updated : 20 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to implement a JavaScript program that will return the highest integer value that the number can go to without losing precision.

Below are the three approaches using which we will get the highest integer value without losing precision

Approach 1: Using Number.MAX_SAFE_INTEGER Constant

The MAX_SAFE_INTEGER constant in JavaScript is the property of the Number object. This constant holds the maximum safe integer. The safe integer is nothing but that any integer greater than this value may lose precision when represented as a number type in JavaScript.

Syntax:

Number.MAX_SAFE_INTEGER

Example: This example implements the above-mentioned approach

Javascript




const maxInteger = () => {
    return Number.MAX_SAFE_INTEGER;
};
console.log(
    `Max Safe Integer is: ${maxInteger()}`
);


Output

Max Safe Integer is: 9007199254740991





Approach 2: Using Mathematical Operation

In this approach, we are using the mathematical operation of printing the JavaScript’s highest integer value that a number can go to without losing precision. Here we have used the operation 2 ** 53 – 1 to generate the highest integer value.

Syntax:

return  2 ** 53 - 1

Example: This example implements the above-mentioned approach

Javascript




const maxInteger = () => {
    return 2 ** 53 - 1;
};
console.log(
    `Max Safe Integer is: ${maxInteger()}`
);


Output

Max Safe Integer is: 9007199254740991





Approach 3: Using User-Defined Function

In this method, we have used the user-defined function along with the loop to double the n until 1 no longer changes the value. This is a completely raw method to print JavaScript’s highest integer value.

Syntax:

while (n + 1 !== n) {
n *= 2;
}

Example: This example implements the above-mentioned approach

Javascript




const maxInteger = () => {
    let n = 1;
    while (n + 1 !== n) {
        n *= 2;
    }
    return n - 1;
};
console.log(
    `Max Safe Integer is: ${maxInteger()}`
);


Output

Max Safe Integer is: 9007199254740991







Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads