3

I did not find a better name for this question...

I want to check if two numbers are either both smaller than 0, both 0 or both greater than 0. Is there an easier way than this?

if (nr0 < 0 && nr1 < 0 || nr0 == 0 && nr1 == 0 || nr0 > 0 && nr1 > 0) {
    //do smth...
}
IceRevenge
  • 1,451
  • 18
  • 33

3 Answers3

14

For readability and simplicity I would suggest:

if (Math.sign(nr0) == Math.sign(nr1)) {
    //...
}

From MDN:

If the argument is a positive number, negative number, positive zero or negative zero, [Math.sign] will return 1, -1, 0 or -0 respectively. Otherwise, NaN is returned.

Ollin Boer Bohan
  • 2,296
  • 1
  • 8
  • 12
3

You can multiply the numbers and check the multiplication should be positive (this will cover both being negative and both being positive) or they should be equal (which will cover the 0 case)

if(nr1*nr2 > 0 || (nr1 === nr2)){
    console.log("On the same side of number scale");
}
void
  • 36,090
  • 8
  • 62
  • 107
1

One way would be:

if ( nr0 * nr1 > 0 || (nr0 == 0 && nr1 == 0)) {
    // do sth...
}
Bibek Shah
  • 419
  • 4
  • 19