Forum OpenACS Development: Problem with function Expr of TCL

Collapse
Posted by Giancarlo Lori on
I' m developing an I have a strange problem.
Following the simple code:

set tcl_precision 5

set addendo_1 123.22
set addendo_2 456.11

set totale [expr $addendo_2 + $addendo_1];

If I execute this script in a web page I have the following result: 579.33000000000004

If I execute this script with shell I have the correct result 579,33

Can explain me what's happen?
I can't understand where is the problem.
Thanks in advance

Collapse
Posted by Stefan Sobernig on
Lori,


Can explain me what's happen?
I can't understand where is the problem.

You are missing that your script snippet is evaluated in a different context in a whatever you mean by a "web page" than in tclsh. i assume that you are referring to a *.{adp|tcl} pair (but this is equally valid for the developer shell etc.)?

tcl_precision is a global tcl variable (global reads the top-level, "::" namespace). the adp templating mechanism in aolserver/openacs and helpers such as ad_form etc. evaluate scripts in nested tcl namespaces. So, you would need to be explicit about mutating tcl_precision in the global namespace, rather than setting a so-named variable in the current, anonymous namespace. E.g., either by ...

global tcl_precision
set tcl_precision 5

... or ...

set ::tcl_precision 5

However, using tcl_precision that way is considered bad style as it might affect other scripts evaluated in the interpreter of the current connection thread and, more importantly, is simply not needed! Just make sure, you format the final string according to your needs:

% set totale [expr 123.22 + 456.11]
579.33000000000004
% format %.2f $totale
579.33

this is what you want: calculating at high precision, then customising the string representation for presentation.

//stefan

Collapse
Posted by Stefan Sobernig on
Sorry, mixed up your first and last name, Giancarlo!