Positive Number to Negative Number in JavaScript?

后端 未结 13 1637
误落风尘
误落风尘 2020-12-13 05:16

Basically, the reverse of abs. If I have:

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


        
相关标签:
13条回答
  • 2020-12-13 05:46
    var x = 100;
    var negX = ( -x ); // => -100
    
    0 讨论(0)
  • 2020-12-13 05:46

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

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

    Of course you could make this a function like this

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

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

    Hope this helps! Math.abs will likely work for you but if it doesn't this little

    0 讨论(0)
  • 2020-12-13 05:47

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

    0 讨论(0)
  • 2020-12-13 05:50
    var i = 10;
    i = i / -1;
    

    Result: -10

    var i = -10;
    i = i / -1;
    

    Result: 10

    If you divide by negative 1, it will always flip your number either way.

    0 讨论(0)
  • 2020-12-13 05:55
    num * -1
    

    This would do it for you.

    0 讨论(0)
  • 2020-12-13 05:56

    In vanilla javascript

    if(number > 0)
      return -1*number;

    Where number above is the positive number you intend to convert

    This code will convert just positive numbers to negative numbers simple by multiplying by -1

    0 讨论(0)
提交回复
热议问题