Rounding a number to the nearest 5 or 10 or X

前端 未结 13 1742
臣服心动
臣服心动 2020-11-28 08:11

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         


        
13条回答
  •  悲哀的现实
    2020-11-28 08:31

    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)
    

提交回复
热议问题