0

Consider the following situation where a new number should not exceed or be lower than old number by a threshold. (

const THRESHOLD = 0.6
const number1 = -56.2//old number
const number2 = 56//new number

  function between(num1, num2) {
    return true/false;
  }
const isTooMuchDEviation = between (number1, number2)

Need to handle negative as well as positive numbers. Other instances:

  const number1 = 56.2
    const number2 = 56.7
    Result = false (within threshold)

    const number1 = -56.2
    const number2 = -55.8
    Result = false (within threshold)

    const number1 = 56.2
    const number2 = -55.8
    Result = true (outside threshold)
Kal
  • 1,656
  • 4
  • 26
  • 41

1 Answers1

0

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
Terry
  • 63,248
  • 15
  • 96
  • 118
  • `(-57.2, -55.8)` should return `false`. But your code returns `true`? I guess not `> threshold` but `> Math.abs(threshold * num1)`? Sorry if i am wrong – Miu Sep 30 '22 at 17:12
  • You are indeed wrong. The absolute difference between -57.2 and -55.8 is more than 0.6 and therefore exceeds the threshold and should return true. Multiplying num1 with threshold makes zero sense, as OP is not looking for a relative difference. – Terry Sep 30 '22 at 17:42
  • It seems I misunderstood threshold. Thank you for your reply and explanation :) – Miu Sep 30 '22 at 19:02