Mathf.RoundToInt()

Hi,
I found, that rounding methods (Round and RoundToInt) probably have some issue when rounding threshold .5 value. Every line in example gives different result.

Debug.Log( Mathf.RoundToInt( 10.5f ) ); // result 10
Debug.Log( Mathf.RoundToInt( 11.5f ) ); // result 12

( Unity 5.6.1f1 )

Does anyone have some explanation please? Is this property or error?
Thanks,
T.

2 Likes

On the docs it says: “if the number ends in .5 so it is halfway between two integers, one of which is even and the other odd, the even number is returned.” That’s why it always jumps to 10,12,14 etc…

To be honest I find this really odd, I would have completely assumed it would round to the closest - most floating point units will round upwards if .5 or above

1 Like

Interesting, does this also apply to just System.Math.Round? I have a feeling it doesn’t

Thanks your for replies, mentioning of even and odd I overlooked. But this is bit strange behavior.
System.Math.Round do the same.

Lame, it is indeed strange! I guess you could force it to Floor or Ceil whenever your number ends in 0.5 to get a consistent result

Yeah, I used to just do:

int RoundedValue = (int)( myFloatValue + 0.5f );

That would make sure it would round up if .5 or above and round down otherwise

1 Like

Rounding to the nearest even number is the way banks do it; it minimizes the accrued error by rounding. For example:

1.5 + 2.5 + 3.5 + 4.5

The actual result without rounding would be 12.
If you always round up, it becomes 2 + 3 + 4 + 5, or 14.
If you round to the nearest even, it becomes 2 + 2 + 4 + 4, or 12.

Rounding to the nearest even gets you closer to the actual value than always rounding up does.

6 Likes

@makeshiftwings is right. This is a feature. (I’m generally no Microsoft fanboy, but the C#/.NET team was very, very careful and got a lot of little details like this right.)

Mathf.Round and RoundToInt merely call System.Math.Round, so that’s expected.

–Eric

Check this out if you need any other "options’.

1 Like