How to round an integer up to the nearest multiple of 'multiple' in VB.NET

1 Answer

0 votes
Imports System

Module RoundUpProgram

    '
    '    roundUp(n, multiple)
    '    --------------------
    '    Rounds the integer n *up* to the nearest multiple of `multiple`.
    '
    '    Mathematically:
    '        result = ceil(n / multiple) * multiple
    '
    '    We use integer arithmetic for efficiency:
    '        (n + multiple - 1) / multiple  → smallest integer ≥ n/m
    '
    Function roundUp(n As Integer, multiple As Integer) As Integer
        If multiple <= 0 Then
            ' Defensive programming: avoid undefined behavior.
            ' In real-world code, you'd throw or handle this differently.
            Return n
        End If

        ' Efficient integer rounding up:
        Return ((n + multiple - 1) \ multiple) * multiple
    End Function

    Sub Main()
        Console.WriteLine("roundUp(53, 20)  = " & roundUp(53, 20))
        Console.WriteLine("roundUp(68, 30)  = " & roundUp(68, 30))
        Console.WriteLine("roundUp(7, 100)  = " & roundUp(7, 100))
        Console.WriteLine("roundUp(119, 100) = " & roundUp(119, 100))
        Console.WriteLine("roundUp(781, 100) = " & roundUp(781, 100))
        Console.WriteLine("roundUp(1026, 100) = " & roundUp(1026, 100))
        Console.WriteLine("roundUp(11689, 1000) = " & roundUp(11689, 1000))
    End Sub

End Module


' run:
'
' roundUp(53, 20)  = 60
' roundUp(68, 30)  = 90
' roundUp(7, 100)  = 100
' roundUp(119, 100) = 200
' roundUp(781, 100) = 800
' roundUp(1026, 100) = 1100
' roundUp(11689, 1000) = 12000
'

 



answered Jul 22 by avibootz

Related questions

...