Home > Software engineering >  MidpointRounding.ToZero doesn't work in Unity
MidpointRounding.ToZero doesn't work in Unity

Time:02-15

I need to use different midpoint rounding rules than the default "round to even" Mathf.Round() has. Mathf.Round() doesn't have parameter for midpoint rounding, so I'm using System.Math.Round().

C# has different strategies for midpoint rounding, specified here: https://docs.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=net-6.0 . MidpointRounding.AwayFromZero and (obviously) MidpointRounding.ToEven work in Unity, but others, namely MidpointRounding.ToZero don't work, for some reason ("CS0117: 'MidpointRounding' does not contain a definition for 'ToZero'").

float firstN = ...
float lastN = ...
int begin = (int)Math.Round(firstN, MidpointRounding.AwayFromZero); //works
int end = (int)Math.Round(lastN, MidpointRounding.ToZero);          //doesn't work

I absolutely need to use MidpointRounding.ToZero, there really isn't any alternatives. I would have to rewrite big parts of the code again. Writing my own rounding function just to solve this one problem doesn't sound fun either.

CodePudding user response:

MidpointRounding.ToZero, despite being tacked on to the MidpointRounding enum, does not do what you want it to do either. It just truncates the decimal portion of the number, giving you the closest integer not further away from zero:

 2.4 ==> 2
 2.5 ==> 2
 2.6 ==> 2
-2.4 ==> -2
-2.5 ==> -2
-2.6 ==> -2

So unfortunately it looks like you need a custom rounding method, but it is not difficult:

int i = (d < 0) ? (int)Math.Floor(d 0.5) : (int)Math.Ceiling(d-0.5);

result:

 2.4 ==> 2
 2.5 ==> 2
 2.6 ==> 3
-2.4 ==> -2
-2.5 ==> -2
-2.6 ==> -3

CodePudding user response:

From memory, I believe the directed roundings are fairly new to the framework. I'm not familiar with Unity, but you may want to try changing your target framework if possible.

Alternatively, Math.Truncate should provide identical behavior and I would argue clearer intent.

int end = (int)Math.Truncate(lastN);
  • Related