title: How to find the nearest angle from 0 to 180 and -180 to 0
body: <p>for example my current angle position is 170, I click on the object to rotate it to -170 degrees, here the problem is that after 178, 179, 180, the next number is -180, -179, -178 and so on...</p>
  
  <p>even tough numerically 170 degrees is far from -170 degrees, but visually they look near, an object is rotating the longest way in order to reach that number, for example:</p>
  
  <pre><code>if(currentAngle &lt; targetAngle)
  {
     currentAngle += 1;
  
  }
  
  if(currentAngle &gt; targetAngle)
  {
    currentAngle -= 1;
  }
  </code></pre>
  
  <p>this way I can reach the target angle, but again how to transpass this barrier between 180 and -180, maybe there are a formula for this?</p>
  
  <p><strong>update:</strong></p>
  
  <pre><code>    onclick() {
                          double angle = Math.atan2(dy, dx);
                          targetAngle = (int)Math.toDegrees(angle); //180 to //-179
      }
  
  onFrame() {
  
   //here happens the animation
  
        if(currentAngle &lt; targetAngle)
        {
  
            currentAngle +=1;
  
        }
  
        if(currentAngle &gt; targetAngle)
        {
            currentAngle -= 1;
        }
  }
  </code></pre>
  
  <p>now what if I'am currently on -179 angle degree, and I clicked on 160 angle degree, it should rotate to left to reach that angle as fast as posible, but in my case it is rotating to the right(which is longer), and thats because it is limited from -180 to 179, thus how to break the limits and go from 179 to -180, -181, -182...if you understand what I mean</p>
  
  <p><img src="https://i.stack.imgur.com/26HRH.png" alt="enter image description here"></p>
  
  <p>1) my click handler:</p>
  
  <pre><code>onClick() { 
  
  double angle = Math.atan2(dy, dx);
                      angle = (int)Math.toDegrees(angle);
                      Log.d("test", "angler:" + angle);
                      if(angle &lt; 0)
                      angle += 360;
  }
  </code></pre>
  
  <p>so here I convert the degrees to positive using angle += 360, then:</p>
  
  <p>2) my onFrame handler:</p>
  
  <pre><code>onFrame() {
  
         if(currentAngle != angle)
          {
  
              if(angle &lt; currentAngle)
              {
                  currentAngle -= 5;
              }
              else
              {
                  currentAngle += 5;
              }
            int diff = Math.abs(angle - currentAngle);
              if(diff &lt;= 5)
              {
                  currentAngle = angle; // if its near we put it exact to that angle
              }
              invalidate(); //update the view
          }
  
  
  }
  </code></pre>
  
  <p>thats all I have</p>