Rounding a Number to a Nearest Given Multiple

raklali 236 Reputation points
2022-02-11T15:18:50.127+00:00

I made the following attempt

Public Function RoundToNearestMultiple(ByVal value As Object, ByVal multiple As Object) As Object
           Return (value \ multiple) * multiple
End Function

When I Call the Function as given below, I get the Result as Shown Against Each Call

MsgBox(RoundToNearestMultiple(1936, 1)) '==>1936
MsgBox(RoundToNearestMultiple(1936, 5)) '==>1935
MsgBox(RoundToNearestMultiple(1936, 10)) '==>1930
MsgBox(RoundToNearestMultiple(1936, 100)) ' ==>1900
MsgBox(RoundToNearestMultiple(1936, 500)) ' ==>1500
MsgBox(RoundToNearestMultiple(1936, 1000)) ' ==>1000

Apparently, the Output is not correct.

What is correct way to do the RoundingOf to the Nearest Given Multiple

So I tried the following but am still getting incorrect values

 Public Function RoundToNearestMultiple(ByVal value As Object, ByVal multiple As Object) As Object
        Dim TempMultiple = 1 ^ (Val(Len(Str(multiple))) - 1)
        Return Math.Ceiling((value \ multiple) * TempMultiple)
    End Function

Seems, I need to use both Math.Floor and Math.Ceiling with a If...Else clause.

Developer technologies | VB
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-02-11T16:37:39.373+00:00

    Check another junction:

    Public Function RoundToNearestMultiple(ByVal value As Integer, ByVal multiple As Integer) As Integer
        Return ((value + multiple \ 2) \ multiple) * multiple
    End Function
    

    If you expect negative numbers too, then give details.

    2 people found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. LesHay 7,141 Reputation points
    2022-02-11T16:21:46.977+00:00

    Hi

    What would you expect the result of:

    RoundToNearestMultiple(1950, 100) to be?

    There are several methods, best you check out

    http://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=net-6.0#examples

    Also, saying that something is 'wrong' just because it doesn't agree with your own understanding can sometimes be wrong!

    0 comments No comments

  2. Leon Stanley 96 Reputation points
    2022-02-14T09:39:13.283+00:00

    Simply

    Return Cint(value / multiple) * multiple

    RoundToNearestMultiple(1949, 100) ' =>> 1900
    RoundToNearestMultiple(1950, 100) ' =>> 2000

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.