A positive number to a negative number in JavaScript?

In principle, the reverse side of abs. If I have:

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

No matter which console ALWAYS returns a positive number. How to fix it?

If I do this:

 if($this.find('.pdxslide-activeSlide').index() < slideNum-1){ _selector.animate({left:(-slideNum*sizes.images.width)+'px'},750,'InOutPDX') } else{ _selector.animate({left:(slideNum*sizes.images.width)+'px'},750,'InOutPDX') } 

it works, but it’s NOT β€œDRY” and just stupid to have the whole block of JUST code for -

+50
javascript jquery math
Apr 6 '11 at 23:24
source share
7 answers
 Math.abs(num) => Always positive -Math.abs(num) => Always negative 

Do you really understand that for your code

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

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

This is more like a logical mistake for me.

+103
Apr 6 2018-11-11T00:
source share

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

+56
Apr 6 '11 at 23:27
source share

The basic formula for a positive negative or negative attitude towards a positive:

 i - (i * 2) 
+13
Aug 14 2018-12-12T00:
source share

Are you sure the control is in the if body? As with the condition in if ? Because if this is not the case, the if body will never be executed, and slideNum will remain positive. I'm going to fear that this is probably what you see.

If I try the following in Firebug, it works:

 >>> i = 5; console.log(i); i = -i; console.log(i); 5 -5 

slideNum *= -1 should also work. Like Math.abs(slideNum) * -1 .

+5
Apr 06 '11 at 23:24
source share

To get the 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 negative, you can do the following:

a = ~a + 1;

which will cause a to be -1000.

+4
Jan 01 '15 at 7:34
source share

If you don't like using Math.Abs ​​* -1, you can make this simple statement if: P

 if (x > 0) { x = -x; } 

Of course you could make this function like this

 function makeNegative(number) { if (number > 0) { number = -number; } } 

makeNegative (-3) => -3 makeNegative (5) => -5

Hope this helps! Math.abs will probably work for you, but if it's not so little

+2
Mar 18 '16 at 14:17
source share

Use 0 - x

x is the number you want to invert

+1
Jan 07 '17 at 19:10
source share



All Articles