Code archives/Algorithms/Round a number

This code has been declared by its author to be Public Domain code.

Download source code

Round a number by chwaga2008
Use this function to round any number to the nearest (insert number here).

This was by Stevie G, but I didn't see it up here and I thought some people could use it. Very useful for grid-snapping!

To use:
Round(number, number_to_round_to)

ex: Round(11, 10) will return 10, 11 to the nearest 10 is 10.
Function Round( Number , N )
   If ( Number Mod N ) >= ( N *.5 )
        Number  = ( Ceil( Number / N ) + 1 ) * N
   Else
        Number = Floor( Number / N ) * N
   EndIf
   Return Number
End Function

Comments

N2008
You really don't need the Floor or Ceil since these both operate on integers. You would still want to wrap parts of them in parentheses, but Floor and Ceil are both only useful for floats in this case.


GIB3D2008
Your way didn't work right for me, but thanks (even though this thread is 6 months old) because it got me in the mood to finally do it myself...



Code Archives Forum