Weird behavior with % operator

So i’m calculating some positions and my problem is that this line:

Mathf.Abs(Mathf.Round(pos.x * 100) / 100) % (4 * scale)

returns 115,6 where it should return 0 (115,6/115,6 should give 1). I thought it has to do with some calculation inaccuracies but when i print this line:

Mathf.Abs(Mathf.Round(346.8f * 1000) / 1000)) / (4 * 28.9f)

it returns 3 (as it should). So my question is what’s the diffrence here? i’m not changing any values or anything.

Hello, the modulus operator does not always work as expected with float variables, because it is designed for integers.

Either you cast to integer beforehand, or you use the Mathf.Repeat function, which is designed to do just that:

float x = Mathf.Abs(Mathf.Round(346.8f * 100) / 100);
float y = 4 * 28.9f;

// will not work
Debug.Log(x % y);

// will work
Debug.Log(Mathf.Repeat(x, y));

Thanks i will try that later!