Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positive Number to Negative Number in JavaScript?

People also ask

How do you negative a number in JavaScript?

To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value: let temperature = -42; What we've seen in this section makes up the bulk of how we will actually use numbers.

How do you make a number positive in JavaScript?

Math. abs always makes it a positive whilst taking the ones complement simply inverts the sign.

Is number positive or negative JavaScript?

The Math. sign() method retuns whether a number is negative, positive or zero. If the number is positive, this method returns 1. If the number is negative, it returns -1.

How do you make a negative number positive?

If you subtract a negative number, the two negatives combine to make a positive. −10−(−10) is not −20. Instead, you can think of it as turning one of the negative signs upright, to cross over the other, and make a plus.


Math.abs(num) => Always positive
-Math.abs(num) => Always negative

You do realize however, that for your code

if($this.find('.pdxslide-activeSlide').index() < slideNum-1){ slideNum = -slideNum }
console.log(slideNum)

If the index found is 3 and slideNum is 3,
then 3 < 3-1 => false
so slideNum remains positive??

It looks more like a logic error to me.


The reverse of abs is Math.abs(num) * -1.


The basic formula to reverse positive to negative or negative to positive:

i - (i * 2)

To get a negative version of a number in JavaScript you can always use the ~ bitwise operator.

For example, if you have a = 1000 and you need to convert it to a negative, you could do the following:

a = ~a + 1;

Which would result in a being -1000.


var x = 100;
var negX = ( -x ); // => -100