 ### Author Topic: Round a decimal, to the Power's of 10. Up and Down  (Read 4208 times)

• Guest ##### Round a decimal, to the Power's of 10. Up and Down
« on: 2009-Jan-21 »
Based on code from Dreamora, this rounds a number to a given number of decimal places :

Code: GLBasic [Select]
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
« Last Edit: 2009-Jul-04 by Hemlos »

#### Hemlos

• To boldy go where no pixel has gone before!
• Global Moderator
• Prof. Inline
•       • • Posts: 1635
• Particle Hawk ##### Round a decimal, to the Power's of 10. Up, and Down.
« Reply #1 on: 2009-Jul-04 »
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:
Code: GLBasic [Select]

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: 