dave
dave

Reputation: 15459

Convert a negative number to a positive one in JavaScript

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

Upvotes: 490

Views: 706313

Answers (17)

Sedrak Ghukasyan
Sedrak Ghukasyan

Reputation: 11

How to convert negative numbers to positive and positive numbers to negative using the unary negation operator -.

The unary negation operator - is used to reverse the sign of a number. When applied to a positive number, it makes it negative, and when applied to a negative number, it makes it positive.

const x = -90;
console.log(-x); // 90

const y = 90;
console.log(-y); // -90

Explanation:

  • const x = -90;: Defines a constant variable x with the value -90, a negative number.
  • console.log(-x);: Negates the value of x using the unary negation operator -, resulting in 90, and logs it to the console.
  • const y = 90;: Defines another constant variable y with the value 90, a positive number.
  • console.log(-y);: Negates the value of y, resulting in -90, and logs it to the console.

Upvotes: 0

Adeel Imran
Adeel Imran

Reputation: 13956

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
    

Upvotes: 88

Dillon Burnett
Dillon Burnett

Reputation: 503

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.

Upvotes: 3

sledgeweight
sledgeweight

Reputation: 8095

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

Upvotes: 0

ChrisNel52
ChrisNel52

Reputation: 15143

You could use this...

Math.abs(x)

Math​.abs() | MDN

Upvotes: 1089

Mahdi Bashirpour
Mahdi Bashirpour

Reputation: 18803

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

Upvotes: 7

Combine
Combine

Reputation: 4214

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

Upvotes: 9

Aspect
Aspect

Reputation: 57

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:

// NEGATIVE TO POSITIVE: ******************************************
var x = -24;
var result = x * -1;
console.log(result);

// VICE VERSA: ****************************************************
var x = 58;
var result = x * -1;
console.log(result);

// FLOATING POINTS: ***********************************************
var x = 42.8;
var result = x * -1;
console.log(result);

// FLOATING POINTS VICE VERSA: ************************************
var x = -76.8;
var result = x * -1;
console.log(result);

Upvotes: 1

mabwehz
mabwehz

Reputation: 116

My minimal approach

For converting negative number to positive & vice-versa

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

Upvotes: 2

Mr.X
Mr.X

Reputation: 11

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

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

Upvotes: 1

Atspulgs
Atspulgs

Reputation: 1439

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. :/

Upvotes: 2

Kyle
Kyle

Reputation: 109

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

~--x

Upvotes: 8

MarkD
MarkD

Reputation: 179

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

I find this solution easy to understand.

Upvotes: 16

gnclmorais
gnclmorais

Reputation: 4971

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

Upvotes: 124

Highway of Life
Highway of Life

Reputation: 24321

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;

Upvotes: 30

orlp
orlp

Reputation: 117681

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

Upvotes: 47

Marc B
Marc B

Reputation: 360602

unsigned_value = Math.abs(signed_value);

Upvotes: 22

Related Questions