[javascript] Convert a negative number to a positive one in JavaScript

Is there a math function in JavaScript that converts numbers to positive value?

This question is related to javascript

The answer is


var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ... 

I find this solution easy to understand.


If you'd like to write interesting code that nobody else can ever update, try this:

~--x


I know another way to do it. This technique works negative to positive & Vice Versa

var x = -24;
var result = x * -1;

Vice Versa:

var x = 58;
var result = x * -1;

LIVE CODE:

_x000D_
_x000D_
// NEGATIVE TO POSITIVE: ******************************************_x000D_
var x = -24;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// VICE VERSA: ****************************************************_x000D_
var x = 58;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// FLOATING POINTS: ***********************************************_x000D_
var x = 42.8;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// FLOATING POINTS VICE VERSA: ************************************_x000D_
var x = -76.8;_x000D_
var result = x * -1;_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


For a functional programming Ramda has a nice method for this. The same method works going from positive to negative and vice versa.

https://ramdajs.com/docs/#negate


unsigned_value = Math.abs(signed_value);

I did something like this myself.

num<0?num*=-1:'';

It checks if the number is negative and if it is, multiply with -1 This does return a value, its up to you if you capture it. In case you want to assign it to something, you should probably do something like:

var out = num<0?num*=-1:num; //I think someone already mentioned this variant.

But it really depends what your goal is. For me it was simple, make it positive if negative, else do nothing. Hence the '' in the code. In this case i used tertiary operator cause I wanted to, it could very well be:

if(num<0)num*=-1;

I saw the bitwise solution here and wanted to comment on that one too.

~--num; //Drawback for this is that num original value will be reduced by 1

This soultion is very fancy in my opinion, we could rewrite it like this:

~(num = num-1);

In simple terms, we take the negative number, take one away from it and then bitwise invert it. If we had bitwise inverted it normally we would get a value 1 too small. You can also do this:

~num+1; //Wont change the actual num value, merely returns the new value

That will do the same but will invert first and then add 1 to the positive number. Although you CANT do this:

~num++; //Wont display the right value.

That will not work cause of precedence, postfix operators such as num++ would be evaluated before ~ and the reason prefix ++num wouldnt work even though it is on the same precedence as bitwise NOT(~), is cause it is evaluated from right to left. I did try to swap them around but it seems that prefix is a little finicky compared to bitwise NOT. The +1 will work because '+' has a higher precedence and will be evaluated later.

I found that solution to be rather fun and decided to expand on it as it was just thrown in there and post people looking at it were probably ignoring it. Although yes, it wont work with floats.

My hopes are that this post hasn't moved away from the original question. :/


The minus sign (-) can convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y is visual sugar for x=(y*-1).

var y = -100;
var x =- y;

What about x *= -1? I like its simplicity.


My minimal approach

For converting negative number to positive & vice-versa

_x000D_
_x000D_
var num = -24;_x000D_
num -= num*2;_x000D_
console.log(num)_x000D_
// result = 24
_x000D_
_x000D_
_x000D_


Math.abs(x) or if you are certain the value is negative before the conversion just prepend a regular minus sign: x = -x.


If you want the number to always be positive no matter what you can do this.

function toPositive(n){
    if(n < 0){
        n = n * -1;
    }
    return n;
}
var a = toPositive(2);  // 2
var b = toPositive(-2); // 2

You could also try this, but i don't recommended it:

function makePositive(n){
    return Number((n*-n).toString().replace('-','')); 
}
var a = makePositive(2);  // 2
var b = makePositive(-2); // 2

The problem with this is that you could be changing the number to negative, then converting to string and removing the - from the string, then converting back to int. Which I would guess would take more processing then just using the other function.

I have tested this in php and the first function is faster, but sometimes JS does some crazy things, so I can't say for sure.


I know this is a bit late, but for people struggling with this, you can use the following functions:

  • Turn any number positive

    let x =  54;
    let y = -54;
    let resultx =  Math.abs(x); //  54
    let resulty =  Math.abs(y); //  54
    
  • Turn any number negative

    let x =  54;
    let y = -54;
    let resultx = -Math.abs(x); // -54
    let resulty = -Math.abs(y); // -54
    
  • Invert any number

    let x =  54;
    let y = -54;
    let resultx = -(x);         // -54
    let resulty = -(y);         //  54
    

Multiplying by (-1) is the fastest way to convert negative number to positive. But you have to be careful not to convert my mistake a positive number to negative! So additional check is needed...

Then Math.abs, Math.floor and parseInt is the slowest.

enter image description here

https://jsperf.com/test-parseint-and-math-floor-and-mathabs/1


You can use ~ operator that logically converts the number to negative and adds 1 to the negative:

_x000D_
_x000D_
var x = 3;_x000D_
x = (~x + 1);_x000D_
console.log(x)_x000D_
// result = -3
_x000D_
_x000D_
_x000D_


Negative to positive

var X = -10 ;
var number = Math.abs(X);     //result 10

Positive to negative

var X = 10 ;
var number = (X)*(-1);       //result -10