Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to increments of 2.5?

Tags:

vb.net

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
like image 709
Slee Avatar asked Oct 22 '08 20:10

Slee


People also ask

How do you round to the nearest multiple?

You can use CEILING to round prices, times, instrument readings or any other numeric value. CEILING rounds up using the multiple supplied. You can use the MROUND function to round to the nearest multiple and the FLOOR function to round down to a multiple.

How do you round increments?

Rounding by increments allows you to round a number (up or down) to the nearest increment of n. If n were 25, 26 would be rounded to 25, whereas 49 would be rounded to 50.

Does 0.5 round up or down?

0.5 rounded off to the nearest whole number is 1. Since, the value after decimal is equal to 5, then the number is rounded up to the next whole number. Hence, the whole number of 0.5 will be 1.


2 Answers

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.

like image 140
harpo Avatar answered Oct 26 '22 02:10

harpo


        /*
               This will round up (Math.Ceiling) or down (Math.Floor) based on the midpoint of the increment.  
               The other examples use Math.Ceiling and therefore always round up.
               Assume the increment is 2.5 in this example and the number is 6.13
            */
            var halfOfIncrement = Increment / 2;                                    // 2.5 / 2 = 1.25
            var floorResult = Math.Floor(originalNumber / Increment);               //Math.Floor(6.13 / 2.5) = Math.Floor(2.452) = 2
            var roundingThreshold = (floorResult * Increment) + halfOfIncrement;    //(2 * 2.5) = 5 + 1.25 = 6.25

            if (originalNumber >= roundingThreshold)                                //6.13 >= 6.25 == false therefore take Math.Floor(6.13/2.5) = Math.Floor(2.452) = 2 * 2.5 = 5
                result = Math.Ceiling(originalNumber / Increment) * Increment;
            else
                result = Math.Floor(originalNumber / Increment) * Increment;
like image 25
WAL Avatar answered Oct 26 '22 01:10

WAL