9

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().

Community
  • 1
  • 1
BishopZ
  • 6,269
  • 8
  • 45
  • 58
  • With ES6 you can use `Math.sign()`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign However due to the implementation it has an unfortunate edge case: `Math.sign(-0) === Math.sign(+0)` – johncip Mar 17 '16 at 01:54

4 Answers4

15

You could just do this:

var sign = number && number / Math.abs(number);
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
toxicate20
  • 5,270
  • 3
  • 26
  • 38
4

How about defining a function to do it?

sign = function(n) { return n == 0 ? 0 : n/Math.abs(n); }
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
2

You can divide the number by its absolute and you'll get the sign:

var sign = number && number / Math.abs(number);
Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31
2

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;

  • if n is 0, then 0
  • if n >>> 31 is 1, it was signed, so negativ, and will be negated to -1
  • if n >>> 31 is 0, it was not signed, so positive and will default to 1
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • Note This assumes `n` is Int32, not Long and will fail for negative `n < -(2**31 + 1)`. – Paul S. Nov 19 '12 at 22:33
  • 1
    @PaulS.: Yep, noted the range limitation in my answer. :) – I Hate Lazy Nov 19 '12 at 22:36
  • I didn't mark this as the correct one because it is not super intuitive for most people, but wow it is short. I really like this approach and thank you for posting it! – BishopZ Nov 19 '12 at 22:53
  • @BishopZ: Thanks. I just realized I had one more character than needed, so I updated it. You're right, it's not the most intuitive bit of code. I was mostly just curious to see what I could come up with. :-) – I Hate Lazy Nov 19 '12 at 23:08
  • Note that this fails if -1 < x < 0. Conversion to int rounds to 0 and the sign is lost. – jjrv Feb 21 '14 at 13:53