Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MidpointRounding.ToZero doesn't work in Unity

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://learn.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.

like image 324
DiMarzio Avatar asked Oct 30 '25 01:10

DiMarzio


1 Answers

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
like image 136
D Stanley Avatar answered Nov 01 '25 16:11

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!