Java: Calculating the angle between two points in degrees

Aich picture Aich · Apr 2, 2012 · Viewed 119.8k times · Source

I need to calculate the angle in degrees between two points for my own Point class, Point a shall be the center point.

Method:

public float getAngle(Point target) {
    return (float) Math.toDegrees(Math.atan2(target.x - x, target.y - y));
}

Test 1: // returns 45

Point a = new Point(0, 0);
    System.out.println(a.getAngle(new Point(1, 1)));

Test 2: // returns -90, expected: 270

Point a = new Point(0, 0);
    System.out.println(a.getAngle(new Point(-1, 0)));

How can i convert the returned result into a number between 0 and 359?

Answer

John Ericksen picture John Ericksen · Apr 2, 2012

you could add the following:

public float getAngle(Point target) {
    float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x));

    if(angle < 0){
        angle += 360;
    }

    return angle;
}

by the way, why do you want to not use a double here?