Showing posts with label negative number. Show all posts
Showing posts with label negative number. Show all posts

Sunday, March 9, 2014

Convert a negative number to a positive number


Code sample on pastebin

"Math.abs (Java Platform SE 7 )" ( http://bit.ly/1hWJjy9 )

Consider the following example where we want to calculate the distance between 2 axis coordinates.

int x1 = 200;
int x2 = 300;
int distance = x1 - x2;

The result is distance =  -100.

If we are simply interested in the distance and not whether the distance is a negative, we can use Math.abs to get the absolute (positive) value of distance, like so:

int distance = Math.abs(x1 - x2);

The result is distance =  100.