javamath

Easy way to keeping angles between -179 and 180 degrees


Is there an easy way to convert an angle (in degrees) to be between -179 and 180? I'm sure I could use mod (%) and some if statements, but it gets ugly:


//Make angle between 0 and 360
angle%=360;

//Make angle between -179 and 180
if (angle>180) angle-=360;

It just seems like there should be a simple math operation that will do both statements at the same time. I may just have to create a static method for the conversion for now.


Solution

  • I'm a little late to the party, I know, but...

    Most of these answers are no good, because they try to be clever and concise and then don't take care of edge cases.

    It's a little more verbose, but if you want to make it work, just put in the logic to make it work. Don't try to be clever.

    int normalizeAngle(int angle)
    {
        int newAngle = angle;
        while (newAngle <= -180) newAngle += 360;
        while (newAngle > 180) newAngle -= 360;
        return newAngle;
    }
    

    This works and is reasonably clean and simple, without trying to be fancy. Note that only zero or one of the while loops can ever be run.