Mathf.Round as 1.5, 3, 4.5

Hello,

For build system of my game, i am rounding floats by using Mathf.Round. But i need it to move like:

0.5, 2, 3.5, 5

I mean like Math.Round * 2

Is it possible?

Your title and your example in the description are two different examples. Both examples have a number distance of 1.5 but your second example has a fix offset of 0.5. I’ll explain both cases.

The basic idea is pretty simple. The Round function rounds to the nearest whole number. So all we have to do is scale our input number by our desired number distance, round it and then scale it back.

f = Mathf.Round(f / 1.5f) * 1.5f;

This will round the number “f” to the closest multiple of 1.5. So a value of “1.0” divided by 1.5 is 0.6666 which is rounded to 1 since it’s greater than 0.5. Multiply by 1.5 and you get 1.5. A value of “0.74” divided by 1.5 is about 0.49333 which is rounded down to 0. A value of “3.9” divided by 1.5 is 2.6 which is rounded up to 3. Multiplied by 1.5 and you get 4.5.

In your second example you have an offset of 0.5. This works the same but as an additional pre and post processing step you’re going to subract / add the offset

f = Mathf.Round((f-0.5f) / 1.5f) * 1.5f +0.5f;

Important note: Keep in mind that floating point numbers can not represent all decimal numbers perfectly. Furthermore the greater the number gets the less precise the numbers become. (the total precision stays the same but you get less precision behind the decimal point the more digits you have before it). To get a better understanding of floating point numbers, have a look at this binary representation of floats. I’ve also posted a table to show how the precision of the single precision floating point format changes depending on the size of the number.

ps: I created this EditorWindow for the Unity editor to show the binary representation of floats, doubles and integers.