[bb] Round a number by chwaga [ 1+ years ago ]

Started by BlitzBot, June 29, 2017, 00:28:41

Previous topic - Next topic

BlitzBot

Title : Round a number
Author : chwaga
Posted : 1+ years ago

Description : 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.


Code :
Code (blitzbasic) Select
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 :


N(Posted 1+ 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.


GIB3D(Posted 1+ 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