Rounding a number to the nearest 5 or 10 or X

VbaRounding

Vba Problem Overview


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.

Vba Solutions


Solution 1 - Vba

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

round(X / N)*N

Solution 2 - Vba

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.

Solution 3 - Vba

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

Solution 4 - Vba

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.

Solution 5 - Vba

'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)

Solution 6 - Vba

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.

Solution 7 - Vba

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)

Solution 8 - Vba

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

Solution 9 - Vba

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

Solution 10 - Vba

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

Solution 11 - Vba

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 ------------

Solution 12 - Vba

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

Solution 13 - Vba

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmatt wilkieView Question on Stackoverflow
Solution 1 - VbaVilx-View Answer on Stackoverflow
Solution 2 - Vbamatt wilkieView Answer on Stackoverflow
Solution 3 - VbaAlnitakView Answer on Stackoverflow
Solution 4 - VbaBobView Answer on Stackoverflow
Solution 5 - VbaJoeyView Answer on Stackoverflow
Solution 6 - VbaRaymond MartineauView Answer on Stackoverflow
Solution 7 - VbaJames BerardView Answer on Stackoverflow
Solution 8 - VbaFredouView Answer on Stackoverflow
Solution 9 - VbaOsama Al-MaadeedView Answer on Stackoverflow
Solution 10 - VbaFredouView Answer on Stackoverflow
Solution 11 - VbaanaView Answer on Stackoverflow
Solution 12 - VbaAlexLaforgeView Answer on Stackoverflow
Solution 13 - VbaTHETHINKER1958View Answer on Stackoverflow