Note: This function was originally named Float() as the function was using Floating point option of Format()
Its now renamed as RoundT() being based on Round()
The reason for choosing Round() over Format() is that the latter seems to be less accurate.
Code: Select all
MsgBox % Format( "{:0.3f}", 1.2345 ) ; 1.234 <- incorrect? . "`n" . Round( 1.2345, 3 ) ; 1.235 <- correct!
RoundT() is a simple wrapper for Round(). It works similar to Round() except it trims redundant trailing zeroes from the result,
RoundT( n, p )
n is any number or a numerical result from an mathematical expression.
p is the floating point precision of the result. Max allowed precision is 15, but try to keep it low, like 10 or less.
Round() can produce undesirable results when precision is too high, for eg: MsgBox % Round( 100, 19 ) ; returns 99.9999999996264960000
The Function with sample calls:
Code: Select all
RoundT( n, p:=6 ) { ; By SKAN on D289 @ goo.gl/Q7zQG9
Return ( p<1 ? Round(n,p) : SubStr(n:=Round(n, p), 1, -1-p) )
. ( p<1 ? "" : (n:=RTrim(SubStr(n, 1-p, p), 0)) ? ("." . n) : "" )
}
; usage samples
MsgBox % RoundT( -000000123.4560000 ) ; removes redundant leading/trailing zeroes
MsgBox % RoundT( 100.) ; removes the dot
MsgBox % RoundT( 100 ) ; changes nothing
MsgBox % RoundT( 86400/24 ) ; Total minutes in a day
MsgBox % RoundT( 123.56, 0 ) ; Rounds off to integer
MsgBox % RoundT( Sqrt(2), 15 ) ; maximum precision of 15