BASIC

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

MrTAToad

  • Guest
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 »

Offline Hemlos

  • To boldy go where no pixel has gone before!
  • Global Moderator
  • Prof. Inline
  • *******
  • Posts: 1578
  • Particle Hawk
    • View Profile
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:
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:




[attachment deleted by admin]
« Last Edit: 2009-Jul-04 by Hemlos »
Volume_of_Earth(km^3) = 4/3*3.14*POW(6371.392896,3)

MrTAToad

  • Guest
Looks good!