Rotating 90 degrees perfectly via coroutine function?

I’m trying to rotate a cube by 90 degrees on a button press, over a period of a few seconds. I pieced togethor a bit of code from various answers on here, and it seems to work alright.

Except, it never rests perfectly on zero degrees. It always goes to exactly 270 degrees, usually to exactly 90 and 180, but never to exactly 0 (i’ve seen it anywhere from -8 to 6!) Surely there must be a way with this code to animate it going exactly 90 degrees every button press, with no offset?

using UnityEngine;
using System.Collections;

public class Cube2 : MonoBehaviour {
	public float DegreesPerSecond = 180f; // degrees per second
    private Vector3 currentRot, targetRot;
    private bool rotating = false;

	// Use this for initialization
	void Start () {
		currentRot = transform.eulerAngles;
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetButtonDown("RotateCube") ) {
			StartCoroutine(Rotate());
		}
	}

	IEnumerator Rotate(){
    	if (!rotating)  {
        	rotating = true;  // set the flag
         	targetRot.y = currentRot.y + 90; // calculate the new angle
         	
         	while (currentRot.y < targetRot.y){
             	currentRot.y = Mathf.MoveTowardsAngle(currentRot.y, targetRot.y, DegreesPerSecond * Time.deltaTime);
             	transform.eulerAngles = currentRot;
             	yield return null;
         	}

       		rotating = false;
     	}
	}
}

I tried setting the “while” condition to currentRot.y <= targetRot.y, but that broke it after 1 button press. You would think there would be an easy way to animate a rotation of 90 degrees on a button press, evidently not though!!

The problem is that you might be at 89.999 degrees, and next time round the loop DegreesPerSecond * time.deltaTime giving you are result greater than 90.0. If this happens then you want to back-up to 90.0. I have some code that does this from ages ago. (Now I look at it I can’t remember why I did this. I’m basically letting angleInc be the normal rotation, and if that takes us too far, back it down to a value that will give is 90.0f.

bool done = false;
float angleInc = DegreesPerSecond * Time.deltaTime;
rotation += angleInc;

if (rotation > 90.0f){ // gone too far
    float old = angleInc;
    rotation -= angleInc;
    angleInc = 90.0f - rotation;
    rotation += old; //Feb15, not sure we need this
    done = true;
}
				
rotator.transform.Rotate(Vector3.forward * angleInc);

My code gets hit by Update() every frame, I don’t do what you do with IEnumerate, although I think your approach is better.