Check if two numbers are both positive or both negative [duplicate]
Clash Royale CLAN TAG#URR8PPP
Check if two numbers are both positive or both negative [duplicate]
This question already has an answer here:
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...
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
3 Answers
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");
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.
Math.sign
One way would be:
if ( nr0 * nr1 > 0 || (nr0 == 0 && nr1 == 0))
// do sth...
Thankyou for correcting.
– Bibek Shah
Aug 10 at 16:05