7 Replies Latest reply on Jun 11, 2013 11:12 AM by Peter Kahrel

# Which of 2 numbers are closest to 0

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

• ###### 1. Re: Which of 2 numbers are closest to 0
```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.

• ###### 2. Re: Which of 2 numbers are closest to 0

Or this:

```function minMagnitude(a, b) {
return Math.min (Math.abs(a), Math.abs(b))
}
```

Peter

• ###### 3. Re: Which of 2 numbers are closest to 0

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

• ###### 4. Re: Which of 2 numbers are closest to 0

Thanks dln385

This was exactly what I needed.

And yes, Peters code returns the abs number - not the original

dln385,

can you explain your first code?

I understand what your codes are doing (I actually wrote the last code that you wrote, but... its pretty long for no reason)

But what does

? a : b

mean?

Thanks!

• ###### 5. Re: Which of 2 numbers are closest to 0

It's called the ternary conditional operator. (That a bit of a mouthful.)

The syntax looks like this:

```condition ? expr1 : expr2
```

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Op erator

• ###### 6. Re: Which of 2 numbers are closest to 0

Wow, great!

Thanks for the explanation

and Thanks for the site!!!

• ###### 7. Re: Which of 2 numbers are closest to 0

> And yes, Peter's code returns the abs number - not the original

Indeed! Hadn't spotted that.