Make a negative number positive
You're looking for absolute value, mate. Math.abs(-5)
returns 5...
The concept you are describing is called "absolute value", and Java has a function called Math.abs to do it for you. Or you could avoid the function call and do it yourself:
number = (number < 0 ? -number : number);
or
if (number < 0)
number = -number;
Just call Math.abs. For example:
int x = Math.abs(-5);
Which will set x
to 5
.
Note that if you pass Integer.MIN_VALUE
, the same value (still negative) will be returned, as the range of int
does not allow the positive equivalent to be represented.