Get the Sum result in NEGATIVE of positive integers

1.3k Views Asked by At

I am adding two numbers with jQuery and I need to get the result in NEGATIVE even if the integers are positive, i.e

var sum = (5 + 10);
console.log(sum)  // Expected result is -15
                  // Current result is 15

Tried concatenating like

sum = '-' + (a + b) // But since the string is being added to number it's not working the expected way. 

Need a little help on the same. Thanks

3

There are 3 best solutions below

1
Tushar On

Don't use - as string, when you use '-' with + operator, the number is casted to string and the result will be '-15' as string. In this case + operator is used as string concatenation operator.

Using '-' in the expression, you're not using this as operator, it is string. Use - without quotes to use it as arithmetic minus operator.

var sum = -(a + b); // -15

This will give you the negated result. If the result of the expression is itself negative e.g. (-10 + 5) above expression will give you result 5.

In case if you always want the negative result

var sum = -(a + b) >= 0 ? (a + b) : -(a + b);
0
Tyler On

The negative sign - is a valid operator in Javascript, so there is no need to use it as a string.

You can do:

var sum = -(5 + 10);

Which is how you would declare a negative number:

var negativeNumber = -123;

Grouping has the highest precedence of any operators in Javascript, so your addition would be done first, and then the subtraction would be applied.


Or if you want it to look nicer mathematically you could multiply by a negative one:

var sum = (5 + 10) * -1;

As @Hanky 웃 Panky points out in his answer, you might want to check to see if your sum is already negative, before applying a negation.

3
J-D On

You can achieve this with simple multiplication of result with -1.

var num_1 = 10;
var num_2 = 20;
var Negative = -1

var result = (parseInt(num_1) + parseInt(num_2)) * Negative;

The output would be -30