Wednesday, February 4, 2026
HomeLanguagesJavascriptHow to check two numbers are approximately equal in JavaScript ?

How to check two numbers are approximately equal in JavaScript ?

In this article, we are given two numbers and the task is to check whether the given numbers are approximately equal to each other or not. If both numbers are approximately the same then print true otherwise print false.

Example:

Input:  num1 = 10.3
        num2 = 10

Output: true

Approach: To check whether the numbers are approximately the same or not, first, we have to decide the epsilon value. Epsilon is the maximum difference between two numbers, if the difference between the numbers is less than or equal to epsilon then the numbers are approximately equal to each other. So first we create a function named checkApprox which takes three arguments num1, num2, and epsilon. Now check the absolute difference between num1 and num2 is less than epsilon or not.

Example 1: This example shows the above-explained approach.

Javascript




<script>
    const checkApprox = (num1, num2, epsilon) => {
      
      // Calculating the absolute difference
      // and compare with epsilon
      return Math.abs(num1 - num2) < epsilon;
    }
      
    console.log(checkApprox(10.003, 10.001, 0.005));
</script>


Output:

true

Example 2: In this example, we will check if the numbers are equal using the Math.abs() method.

Javascript




<script>
    const checkApprox = (num1, num2, epsilon = 0.004) => {
      return Math.abs(num1 - num2) < epsilon;
    }
      
    console.log(checkApprox(Math.PI / 2.0, 1.5708));
</script>


Output:

true

Example 3: This example checks for the numbers if they are equal or not.

Javascript




<script>
    const checkApprox = (num1, num2, epsilon = 0.004) => {
      return Math.abs(num1 - num2) < epsilon;
    }
      
    console.log(checkApprox(0.003, 0.03));
</script>


Output:

false
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
125 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11980 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12066 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6935 POSTS0 COMMENTS
Umr Jansen
6919 POSTS0 COMMENTS