Advertisement
Advertisement


Make a negative number positive


Question

I have a Java method in which I'm summing a set of numbers. However, I want any negatives numbers to be treated as positives. So (1)+(2)+(1)+(-1) should equal 5.

I'm sure there is very easy way of doing this - I just don't know how.

2017/08/08
1
148
8/8/2017 9:59:15 AM

Accepted Answer

Just call Math.abs. For example:

int x = Math.abs(-5);

Which will set x to 5.

2014/11/23
370
11/23/2014 7:53:53 AM


You're looking for absolute value, mate. Math.abs(-5) returns 5...

2009/01/29

Use the abs function:

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);
2009/01/29

This code is not safe to be called on positive numbers.

int x = -20
int y = x + (2*(-1*x));
// Therefore y = -20 + (40) = 20
2019/06/06

Try this (the negative in front of the x is valid since it is a unary operator, find more here):

int answer = -x;

With this, you can turn a positive to a negative and a negative to a positive.


However, if you want to only make a negative number positive then try this:

int answer = Math.abs(x);

OR, if you would prefer not to use the abs() method for some reason then try this:

int answer = Math.sqrt(Math.pow(x, 2));

Hope it helps! Good Luck!

2018/11/12

Are you asking about absolute values?

Math.abs(...) is the function you probably want.

2009/01/29

Source: https://stackoverflow.com/questions/493494
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]