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 chwaga
(Posted 19 years ago)
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

Nilium
(Posted 19 years ago)
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.

GIA_Green_Fire_
(Posted 18 years ago)
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...
Const Number# = 102
Const Nearest# = 10

Print Number+" to the Nearest "+Nearest
Print Round(Number,Nearest)
WaitKey
End

;The variables in Round, Ex. (Number#, Nearest#) are local
;so they won't effect or won't be effected by the 
;Const Number# and Const Nearest#

Function Round(Number#, Nearest#)
	Number = Int(Number/Nearest)*Nearest
	Return Number
End Function


Code Archives Forum