// 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.