Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way in Javascript to get just the sign of a number? [duplicate]

Tags:

javascript

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

like image 660
BishopZ Avatar asked Nov 19 '12 22:11

BishopZ


4 Answers

You could just do this:

var sign = number && number / Math.abs(number);
like image 151
toxicate20 Avatar answered Nov 02 '22 22:11

toxicate20


How about defining a function to do it?

sign = function(n) { return n == 0 ? 0 : n/Math.abs(n); }
like image 22
Madara's Ghost Avatar answered Nov 02 '22 23:11

Madara's Ghost


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

var sign = number && number / Math.abs(number);
like image 41
Kirill Ivlev Avatar answered Nov 02 '22 22:11

Kirill Ivlev


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
like image 27
I Hate Lazy Avatar answered Nov 02 '22 23:11

I Hate Lazy