Friday, 12 April 2024 09:19

how to compare two floating point numbers in JavaScript properly

Written by 
Rate this item
(0 votes)

In JavaScript, comparing floating-point numbers can sometimes lead to unexpected results due to the way floating-point arithmetic is handled by computers. This is because floating-point numbers are represented with a finite number of bits, which can lead to rounding errors.

This way is best to compare two floating-point numbers in JavaScript:

 // Define two floating-point numbers

const num1 = 0.1 + 0.2; const num2 = 0.3;

// Define a function to compare floating-point numbers with a certain tolerance function areEqual(num1, num2, tolerance = Number.EPSILON) { return Math.abs(num1 - num2) < tolerance; }

// Compare the two numbers if (areEqual(num1, num2)) { console.log("The numbers are equal."); } else { console.log("The numbers are not equal."); }

In this example, Number.EPSILON represents the smallest interval between two representable numbers. By default, it's used as the tolerance when comparing floating-point numbers. You can adjust the tolerance based on your specific needs.

It's important to note that direct comparison (num1 === num2) may not work reliably due to rounding errors. Using a tolerance-based approach as shown above is more robust for comparing floating-point numbers.

Read 83 times Last modified on Friday, 12 April 2024 09:25
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.

Latest discussions

  • No posts to display.