I would like to round my gameobjects transform.position floats to .5 when I move. I was able to get it to work with Mathf.RoundToInt but with Mathf.Round/2 the gameobject never makes it to 0.5 resets back to 0 and then locks up. What am I doing wrong with my code?

Hi, I think you’re wanting Mathf.Round(). It still rounds to the nearest while number, but doesn’t return an integer.

To round how you’re wanting, I’d make a function like this :

public static float RoundToNearestHalf(float a)
{
return a = Mathf.Round(a * 2f) * 0.5f;
}

Any float you pass into that function will be rounded to the nearest 0.5

Another thing to note, you’ll want to at least occasionally check and correct the actual values in transform.position, to ensure they’re still rounded to 0.5. Depending how you move that transform, you will get consecutive rounding errors, which can quickly add up and result in inaccurate placement of your object.

If you’re dealing with VERY large values, this function might be a safer option:

public static float RoundToNearestHalfSafer(float a)
{
return a = a - (a % 0.5f);
}

This version uses the modulus operator to get the remainder of dividing “a” by 0.5, then subtracts that from “a” to get a rounded value.

public static float Half(float value)
{
return Floor(value) + 0.5f;
}
// Standalone Floor Function, Not necessary, but good for beginners to understand how it works.
public static float Floor(float value)
{
return value > 0 ? (value - value % 1) : (value - (value % -1));
}