Rounding a number to the nearest 5 or 10 or X

前端 未结 13 1746
臣服心动
臣服心动 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:17

    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
    

提交回复
热议问题