Skip to main content
Inspiring
June 11, 2013
Answered

Which of 2 numbers are closest to 0

  • June 11, 2013
  • 1 reply
  • 1468 views

Hello,

Although this might be a general question, I would like to seek some help from the forum.

I am running a script and I have a function which receives 2 numbers (variables)

I would like to know which of the 2 is closest to 0

I.e., if the numbers are 5, -2 = -2 is closer etc.

Is there someone who can offer some method or function that can help me with this.

(I made 2 loops that counts how many times it took the number to get to 0

but I believe there is a better way.)

Thanks,

Davey

This topic has been closed for replies.
Correct answer dln385

function minMagnitude(a, b) {

    return Math.abs(a) < Math.abs(b) ? a : b;

}

If you're unfamiliar with that syntax, here's an equivalent method:

function minMagnitude(a, b) {

    if (Math.abs(a) < Math.abs(b)) {

        return a;

    } else {

        return b;

    }

}

And here's another equivalent method:

function minMagnitude(a, b) {

    var absA;

    if (a < 0) {

        absA = -a;

    } else {

        absA = a;

    }

   

    var absB;

    if (b < 0) {

        absB = -b;

    } else {

        absB = b;

    }

   

    if (absA < absB) {

        return a;

    } else {

        return b;

    }

}

But really, I would stick with the first one.

1 reply

dln385Correct answer
Inspiring
June 11, 2013

function minMagnitude(a, b) {

    return Math.abs(a) < Math.abs(b) ? a : b;

}

If you're unfamiliar with that syntax, here's an equivalent method:

function minMagnitude(a, b) {

    if (Math.abs(a) < Math.abs(b)) {

        return a;

    } else {

        return b;

    }

}

And here's another equivalent method:

function minMagnitude(a, b) {

    var absA;

    if (a < 0) {

        absA = -a;

    } else {

        absA = a;

    }

   

    var absB;

    if (b < 0) {

        absB = -b;

    } else {

        absB = b;

    }

   

    if (absA < absB) {

        return a;

    } else {

        return b;

    }

}

But really, I would stick with the first one.

Peter Kahrel
Community Expert
Community Expert
June 11, 2013

Or this:

function minMagnitude(a, b) {

    return Math.min (Math.abs(a), Math.abs(b))

}

Peter

Inspiring
June 11, 2013

I considered that, but it actually doesn't work. minMagnitude(5,-2) should return -2, not 2.