Site Tools


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

developer:scriptsamples:roundtonearest [2015/09/14] (current)
Line 1: Line 1:
 +====== Rounding Numbers by an Increment ======
 +> **Developer:​** [[developer:​rhinoscript|RhinoScript]]
 +> **Summary:​** //​Demonstrates how to round a number up or down by a desired increment.//​
 +
 +====Summary====
 +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.
 +
 +====Code====
 +
 +<code vb>
 + '​ 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
 +   Else
 +     If (bRoundUp = True) Then
 +      Temp = Int(Temp) + 1
 +     Else
 +      Temp = Int(Temp)
 +     End If
 +     ​RoundToNearest = Temp * RoundAmt
 +   End If
 + End Function
 +
 +</​code>​
 +====Example====
 +
 +<code vb>
 + ​MsgBox RoundToNearest(1.36,​ 0.25, True)
 + ​MsgBox RoundToNearest(1.36,​ 0.05, False)
 + ​MsgBox RoundToNearest(1.36,​ 0.75, True)
 +</​code>​
 +
 +
 +
 +{{tag>​Developer RhinoScript}}
  
developer/scriptsamples/roundtonearest.txt ยท Last modified: 2015/09/14 (external edit)