Reputation: 22167
How to detect if positive or nagative changes ?
Example :
1
change to 2
= false
0
change to 1
= false
Because both are positive numbers
1
change to -1
= true
0
change to -1
= true
Because positive change to negative
-1
change to 0
= true
-1
change to 1
= true
Because negative change to positive
I do like..
var a_test,b_test;
if(a<0) {
a_test = 'negative';
} else {
a_test = 'positive';
}
if(b<0) {
b_test = 'negative';
} else {
b_test = 'positive';
}
if(a_test!==b_test) {
alert('Yeah!');
}
For test : http://jsfiddle.net/e9QPP/
Any better coding for do something like this ?
Wiki : A negative number is a real number that is less than zero
Upvotes: 4
Views: 2740
Reputation: 301
Maybe a bit late, but I had the same problem.
Assuming you now that a and b are numbers why not:
if(a < 0 ? b >=0 : b < 0){
// your code here
}
Upvotes: 1
Reputation: 17013
Based on your criteria, it seems you simply want to compare the signs of the two numbers. The sign is stored in the highest bit of the number, therefore, to compare the signs, we can simply shift all the other bits off the number, and compare the signs.
Numbers in JavaScript are 64 bit (double
), so we need to shift off the 63 bits preceding the sign:
if (a >>> 63 !== b >>> 63) alert('Yeah!');
Here is a jsFiddle demo
Here is a jsPerf comparison based on the 4 methods offered here.
Please note that this assumes that the numbers are 64 bit. I don't know if the spec restricts it to 64-bit, but it's plausible that there are browsers out there (or will be one day) where numbers are represented by perhaps a 128-bit number or greater.
Upvotes: 1
Reputation: 382150
You seem to want
if (a*b<0) alert('Yeah!');
If you want to consider 0
as a positive number, you may use
if (a*b<0 || (!(a*b) && a+b<0)) alert('Yeah!');
Upvotes: 4
Reputation: 239473
According to the Zen of Python
,
Readability counts.
So, I present more readable and code-review passing version
if (a < 0 && b >= 0 || a >= 0 && b < 0) {
alert("Yeah");
}
Upvotes: 5
Reputation: 41757
Taking a suitable sign function:
function sign(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
}
Then your problem can be expressed in clear and (hopefully) simple terms:
if (sign(a) !== sign(b)) {
// Your code here
}
Upvotes: 3