GLBasic forum
Codesnippets => Math => Topic started by: MrTAToad on 2009Jan21

Based on code from Dreamora, this rounds a number to a given number of decimal places :
DEBUG "Round : "+round(10.34,1)+"\n"
END
FUNCTION roundToDP:number,dp%
LOCAL t
LOCAL result
t=POW(10,dp%)
result=INTEGER(number*t+0.5*SGN(number))
RETURN (result/t)
ENDFUNCTION

Thanks Toad, your function rounds the numbers up, like bankers math.
If last number is >=0.5 it adds 0.5.
I think that is called bankers rounding or something..it has alot of names actually.
Im not positive, but it might be called ceiling() in C++?
Almost like your function, this function rounds down ( floor() in C++ ? ),
it truncuates the number to the power of 10, and doesnt round up:
FUNCTION DecimalPower: Real_Number, Decimal_Power
//Round Down, a Decimal Number, to the nearest power of 10.
// The Decimal Power must be a power of 10, ie: 1 2 3 4 etc
RETURN INTEGER( Real_Number * POW( 10, Decimal_Power ) ) / POW( 10, Decimal_Power )
ENDFUNCTION
And here is a sample project that shows both functions in action:
[attachment deleted by admin]

Looks good!