Site Tools

Rounding Numbers by an Increment

Developer: RhinoScript
Summary: Demonstrates how to round a number up or down by a desired increment.


This article shows you how to create a procedure that rounds a number up or down by a specified increment. For example, given the number 3.23, rounding to the nearest .05 results in the number 3.25. The procedure in this article accepts any positive rounding increment as a parameter. In addition to rounding numbers to the nearest fractional amount, you can also round to whole numbers, such as 1, 10, or 100.


 ' Function:
 '   RoundToNearest
 ' Description
 '   Rounds a number by an increment
 ' Parameters:
 '   Amt (Number) - number to round
 '   RoundAmt (Number) - increment to which Amt will be rounded
 '   bRoundUp (Boolean) - rounding direction (up or down)
 Function RoundToNearest(Amt, RoundAmt, bRoundUp)
   On Error Resume Next
   Dim Temp : Temp = Amt / RoundAmt
   If Int(Temp) = Temp Then
     RoundToNearest = Amt
     If (bRoundUp = True) Then
      Temp = Int(Temp) + 1
      Temp = Int(Temp)
     End If
     RoundToNearest = Temp * RoundAmt
   End If
 End Function


 MsgBox RoundToNearest(1.36, 0.25, True)
 MsgBox RoundToNearest(1.36, 0.05, False)
 MsgBox RoundToNearest(1.36, 0.75, True)
developer/scriptsamples/roundtonearest.txt ยท Last modified: 2015/09/14 (external edit)