tags:

views:

461

answers:

2

I need to round a value up to the nearest multiple of 2.5.

For example:
6 --> 7.5
7.6 --> 10
etc.

This seems like the best way to do this?

   Function RoundToIncrement(ByVal originalNumber As Decimal, ByVal increment As Decimal) As Decimal

        Dim num = Math.Round(originalNumber / increment, MidpointRounding.AwayFromZero) * increment
        If originalNumber Mod increment <> 0 And num < originalNumber Then
            num += increment
        End If
        Return num

    End Function
+16  A: 

Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5.

You're close.

Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal
    Return Math.Ceiling( orignialNumber / increment ) * increment
End Function

Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.

harpo
Looks to me as though that code is there to adjust values that get rounded down by the first line. But I don't know VB: presumably there's a Math.Ceil or similar that would be better here than Math.Round?
Steve Jessop
Agreed... Math.Ceiling could be substituted for Math.Round to achieve the same effect.
harpo
+4  A: 

Divide the number by 2.5. Round to nearest 1. Multiply by 2.5.

Beware of cumulative errors, and you're all set.

Adam Davis