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
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.
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.
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.
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.
/*
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With