How do I round to the nearest 0.5?

Viewed 154831

I have to display ratings and for that, I need increments as follows:

Input Rounded
1.0 1
1.1 1
1.2 1
1.3 1.5
1.4 1.5
1.5 1.5
1.6 1.5
1.7 1.5
1.8 2.0
1.9 2.0
2.0 2.0
2.1 2.0

and so on...

Is there a simple way to compute the required values?

10 Answers

These lines of code snap a float dx to nearest snap:

if (snap <= 1f)
    dx = Mathf.Floor(dx) + (Mathf.Round((dx - Mathf.Floor(dx)) * (1f / snap)) * snap);
else
    dx = Mathf.Round(dx / snap) * snap;

So if snap is 0.5, value gets rounded to nearest 0.5 value (1.37 goes to 1.5), if it is 0.02, value is rounded to nearest 0.02 ((1.37 goes to 1.38)). If snap is 3, value is rounded to nearest 3 (7.4 goes to 6, 7.6 goes to 9) etc... I use it to quickly snap objects on scene in unity because unity default snapping doesn't seem to work well for me.

This answer is taken from Rosdi Kasim's comment in the answer that John Rasch provided.

John's answer works but does have an overflow possibility.

Here is my version of Rosdi's code:

I also put it in an extension to make it easy to use. The extension is not necessary and could be used as a function without issue.

<Extension>
Public Function ToHalf(value As Decimal) As Decimal
    Dim integerPart = Decimal.Truncate(value)
    Dim fractionPart = value - Decimal.Truncate(integerPart)
    Dim roundedFractionPart = Math.Round(fractionPart * 2, MidpointRounding.AwayFromZero) / 2
    Dim newValue = integerPart + roundedFractionPart
    Return newValue
End Function

The usage would then be:

Dim newValue = CDec(1.26).ToHalf

This would return 1.5

Related