Question

Given numbers like 499, 73433, 2348 what VBA can I use to round to the nearest 5 or 10? or an arbitrary number?

By 5:

 499 ->  500
2348 -> 2350
7343 -> 7345

By 10:

 499 ->  500
2348 -> 2350
7343 -> 7340

etc.

Was it helpful?

Solution 2

Integrated Answer

X = 1234 'number to round
N = 5    'rounding factor
round(X/N)*N   'result is 1235

For floating point to integer, 1234.564 to 1235, (this is VB specific, most other languages simply truncate) do:

int(1234.564)   'result is 1235

Beware: VB uses Bankers Rounding, to the nearest even number, which can be surprising if you're not aware of it:

msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too

Thank you everyone.

OTHER TIPS

It's simple math. Given a number X and a rounding factor N, the formula would be:

round(X / N)*N

To round to the nearest X (without being VBA specific)

N = X * int(N / X + 0.5)

Where int(...) returns the next lowest whole number.

If your available rounding function already rounds to the nearest whole number then omit the addition of 0.5

In VB, math.round has additional arguments to specify number of decimal places and rounding method. Math.Round(10.665, 2, MidpointRounding.AwayFromZero) will return 10.67 . If the number is a decimal or single data type, math.round returns a decimal data type. If it is double, it returns double data type. That might be important if option strict is on.

The result of (10.665).ToString("n2") rounds away from zero to give "10.67". without additional arguments math.round returns 10.66, which could lead to unwanted discrepancies.

'Example: Round 499 to nearest 5. You would use the ROUND() FUNCTION.

a = inputbox("number to be rounded")
 b = inputbox("Round to nearest _______ ")


  strc = Round(A/B)
  strd = strc*B


 msgbox( a & ",  Rounded to the nearest " & b & ", is" & vbnewline & strd)

For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)

Multiples of 5 or x can be done simply by dividing before and multiplying after the round.

If you want to round and keep decimal places, Math.round(n, d) would work.

Here is our solution:

Public Enum RoundingDirection
    Nearest
    Up
    Down
End Enum

Public Shared Function GetRoundedNumber(ByVal number As Decimal, ByVal multiplier As Decimal, ByVal direction As RoundingDirection) As Decimal
    Dim nearestValue As Decimal = (CInt(number / multiplier) * multiplier)
    Select Case direction
        Case RoundingDirection.Nearest
            Return nearestValue
        Case RoundingDirection.Up
            If nearestValue >= number Then
                Return nearestValue
            Else
                Return nearestValue + multiplier
            End If
        Case RoundingDirection.Down
            If nearestValue <= number Then
                Return nearestValue
            Else
                Return nearestValue - multiplier
            End If
    End Select
End Function

Usage:

dim decTotal as Decimal = GetRoundedNumber(CDec(499), CDec(0.05), RoundingDirection.Up)

Simply ROUND(x/5)*5 should do the job.

I cannot add comment so I will use this

in a vbs run that and have fun figuring out why the 2 give a result of 2

you can't trust round

 msgbox round(1.5) 'result to 2
 msgbox round(2.5) 'yes, result to 2 too

something like that?

'nearest
 n = 5
 'n = 10

 'value
 v = 496
 'v = 499 
 'v = 2348 
 'v = 7343

 'mod
 m = (v \ n) * n

 'diff between mod and the val
 i = v-m


 if i >= (n/2) then     
      msgbox m+n
 else
      msgbox m
 end if

Try this function

--------------start----------------

Function Round_Up(ByVal d As Double) As Integer
    Dim result As Integer
    result = Math.Round(d)
    If result >= d Then
        Round_Up = result
    Else
        Round_Up = result + 1
    End If
End Function

-------------end ------------

I slightly updated the function provided by the "community wiki" (the best answer), just to round to the nearest 5 (or anything you like), with this exception : the rounded number will NEVER be superior to the original number.

This is useful in cases when it is needed to say that "a company is alive for 47 years" : I want the web page to display "is alive for more than 45 years", while avoiding lying in stating "is alive for more than 50 years".

So when you feed this function with 47, it will not return 50, but will return 45 instead.

'Rounds a number to the nearest unit, never exceeding the actual value
function RoundToNearestOrBelow(num, r)

    '@param         num         Long/Integer/Double     The number to be rounded
    '@param         r           Long                    The rounding value
    '@return        OUT         Long                    The rounded value

    'Example usage :
    '   Round 47 to the nearest 5 : it will return 45
    '   Response.Write RoundToNearestBelow(47, 5)

    Dim OUT : OUT = num

    Dim rounded : rounded = Round((((num)) / r), 0) * r

    if (rounded =< num) then
        OUT = rounded
    else
        OUT = rounded - r
    end if

    'Return
    RoundToNearestOrBelow = OUT

end function 'RoundToNearestOrBelow

To mimic in Visual Basic the way the round function works in Excel, you just have to use: WorksheetFunction.Round(number, decimals)

This way the banking or accounting rounding don't do the rounding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top