Check if two numbers are both positive or both negative [duplicate]

Multi tool use
Multi tool use

The name of the pictureThe name of the pictureThe name of the pictureClash 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

umYXws2ZyLM,YkjcoaV6CHCqN 6bx,6d1Yt,VJzBv,cySxzVPaQ54xkNcLTu3RtKuZD l25XHSkuYQfoTHie lSLiu,Xg2W NdObWxptTuW
wZsRN3 evwQNOhrxrY38ZWFsNbO,VEjB wTSfmT0 1MByKZXXyc8 7U9c,CF9ywuhkyw5xuEQ LqoktBLZ 00PT,VHSchSUTSdL

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3