Rounding a number to the nearest 5 or 10 or X

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

    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.

提交回复
热议问题