Possible Duplicate:
Number.sign() in javascript
Given some number variable, what is the easiest way to determine it's sign?
I keep ending up with code like this:
var direction = (vector[0] > 0) ? 1: (vector[0] < 0) ? -1: 0;
It seems less than elegant, when all I want is a -1 if the number is negative, 1 if positive and a 0 if it is 0.
By "easiest" I really mean elegant or less typing.
Alternatively, maybe there is a way to increase a value absolutely. Like if the number is negative, then subtract 1 from it, and if it is positive to add one to it. Math.abs() provides the absolute value, but there is no way to convert it back to a signed number once you run Math.abs().
You could just do this:
var sign = number && number / Math.abs(number);
How about defining a function to do it?
sign = function(n) { return n == 0 ? 0 : n/Math.abs(n); }
You can divide the number by its absolute and you'll get the sign:
var sign = number && number / Math.abs(number);
If you want a shorter way, and you know it's a number, and you don't mind being limited to a signed 32 bit range, you can do this:
n ? -(n >>> 31) || 1 : 0;
n
is 0
, then 0
n >>> 31
is 1
, it was signed, so negativ, and will be negated to -1
n >>> 31
is 0
, it was not signed, so positive and will default to 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With