Forum OpenACS Q&A: easy tcl question...

Collapse
Posted by David Kuczek on
I have read through my Welch Practical Programming in TCL and TK book,
but just haven't found an answer to this cheap question...

I want to round a numeric to a certain digit after the floating point.

Example: I have 7.14123 and I need either 7.1 or 7.14 or 7.141 etc.

Thanks

Collapse
Posted by Michael A. Cleverly on
Here's a proc that will do it:
proc round_to_n {x n} {
    if {$n < 0} {
        error "n must be greater than or equal to 0"
    } elseif {$n == 0} {
        return [expr {int(round($x))}]
    } else {
        return [expr {round($x * pow(10,$n))/pow(10,$n)}]
    }
}
From tclsh:

% set x 7.14123
7.14123
% round_to_n $x 0
7
% round_to_n $x 1
7.1
% round_to_n $x 2
7.14
% round_to_n $x 3
7.141

Collapse
Posted by Louis Zirkel on
How about using something like this:
set i 7.14123
set j 3
set k [format "%.*f" $j $i]
Where you can set j to be any number of decimal places to pad to.
Collapse
Posted by David Kuczek on
Muchos gracias,

both work... great.

Collapse
Posted by Louis Zirkel on
Michael and I were discussing this last night and through some timing Michael found that his solution was a couple of microseconds faster than mine, so if performance is important you'll want to use his code. 😉