That is just a matter of using Math.abs()
to compare your two numbers, which will return the absolute difference between them: and then check if the difference exceeds a given threshold. You can write a function that accepts three arguments and will return a boolean indicating if a number has exceeded the threshold or not.
Warning: JS has quirks with floating point numbers, and that's something you need to be aware of: How to deal with floating point number precision in JavaScript?
Here is a proof-of-concept example whose output matches your expected results based on the provided number pairs:
const THRESHOLD = 0.6;
function isDiffBeyondThreshold(num1, num2, threshold) {
return Math.abs(num1 - num2) > threshold;
}
console.log(isDiffBeyondThreshold(56.2, 56.7, THRESHOLD)); // false
console.log(isDiffBeyondThreshold(-56.2, -55.8, THRESHOLD)); // false
console.log(isDiffBeyondThreshold(56.2, -55.8, THRESHOLD)); // true
The function above assumes you might want to have a difference threshold in each use case. If your threshold is just a magic constant of 0.6, you can also just use it directly in your function, sacrificing abstraction:
function isDiffBeyondThreshold(num1, num2) {
return Math.abs(num1 - num2) > 0.6;
}
console.log(isDiffBeyondThreshold(56.2, 56.7)); // false
console.log(isDiffBeyondThreshold(-56.2, -55.8)); // false
console.log(isDiffBeyondThreshold(56.2, -55.8)); // true