Unity Tips – Banker’s Rounding

As Unity uses the .NET runtime, both the Mathf.RoundToInt() and Mathf.Round() methods use “Banker’s Rounding”. This is a rounding system that rounds numbers to the nearest even integer when rounding from the midpoint (.5). The “Banker’s Rounding” approach works best when dealing with large quantities of numbers and exists to avoid rounding error. However, this may be not what you’re expecting when you’re working in Unity!

You can use the .NET System.Math library in instead of UnityEngine.Mathf to implement a more conventional rounding system by passing through MidpointRounding.AwayFromZero as an argument to the Math.Round method. Be warned that the default for Round is also “Banker’s Rounding” so if you don’t use this, you will still get the same results as Unity’s version. See below for an example.

(I was stupid in this and forgot to re-comment the netRoundingA, it actually returns 3 which was the whole point of this)

You will also need to cast the return to an int, as the Math.Round method will return a double instead.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s