McNeel Wiki
Rounding Numbers by an Increment
edit · print · help · all topics
Main Pages

AccuRender

Bongo

Brazil r/s

Developer

Flamingo

Penguin

Rhino Blogs

Rhino

Rhino Labs

Search

Languages

Česky

Deutsch

English

Español

Français

Italiano

Polish

日本語

한국어

中文(繁體)

中文(简体)

 
.
DeveloperRhinoScript
SummaryDemonstrates 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

  ' 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

Example

  MsgBox RoundToNearest(1.36, 0.25, True)
  MsgBox RoundToNearest(1.36, 0.05, False)
  MsgBox RoundToNearest(1.36, 0.75, True)
rename · changes · history · subscriptions · lost and found · references · file upload