Need help : Rounding up integer to multiple of a number

  • Thread starter Thread starter Kevin993
  • Start date Start date
K

Kevin993

Guest
Greetings,

with the code below, it is possible to round up an integer to multiple of a number :

Math.Ceiling(number / multiplier) * multiplier

For instance, If the multiplier is 5 and the input is 6 , the result is 10 (multiple of 5).

Another example is 1361 as input , with 12 as multiplier : the result is 1368. So what the above code does is to take the whole number as input and round it to the next multiple of the specified number which is 12 in the previous example.

What If I want to only round up the last n digits of the input ? Let's the a look at the previous example in this case :

1361 is our input. I only need to round up the last n digits (for instance, n=2) of the input which is 61 in this example. So if we take 61 as input to the code above , 12 as the multiplier : the result is 72. Therefore, 1372 is our final result (the round up operation only processed the n last digits of the input)


What I had in my mind was to first reverse the input : 1631, then use

Mid(1631, 1, n)

( n = 2 ) , so the result of the code above is 16. I now reverse the result which is 61. Now I have the last n digits to round it up. So :

Math.Ceiling(61 / 12) * 12

the result of the code above is 72. I now need to replace the last n digits of the input (61) with 72. So :

Dim input_length As Integer = input.ToString.Length

Dim input_first_digits As Integer = input_length - 2 ' (n=2)

Dim result as Integer = Mid(input, 1, input_first_digits) & 72


Is it safe to do so ?

Continue reading...
 
Back
Top