November 28, 2020, 02:30:54 AM

Author Topic: [bb] Round a number by chwaga [ 1+ years ago ]  (Read 471 times)

Offline BlitzBot

  • Jr. Member
  • **
  • Posts: 1
[bb] Round a number by chwaga [ 1+ years ago ]
« on: June 29, 2017, 12:28:41 AM »
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
  1. Function Round( Number , N )
  2.    If ( Number Mod N ) >= ( N *.5 )
  3.         Number  = ( Ceil( Number / N ) + 1 ) * N
  4.    Else
  5.         Number = Floor( Number / N ) * N
  6.    EndIf
  7.    Return Number
  8. 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...
Code: [Select]
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


 

SimplePortal 2.3.6 © 2008-2014, SimplePortal