Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help on convert float to int 1

Status
Not open for further replies.

tomdagliusa

Programmer
May 31, 2000
34
US
I can do the following from the tcl shell:

[HOST]$ tcl
tcl> set x 2.0
tcl> set y [int $x]
tcl> puts $y
2
tcl>

SO, in my script I have:
set valSkew1 [expr $what2chk4 * $RATE_SKEW]
set valSkew [int $valSkew1]

I get the following syntax failure:

WARNING(Mon Jul 29 12:46:36) : Test aborted
WARNING(Mon Jul 29 12:46:36) : invalid command name "int" ; invalid command name "int"
while executing
"int $valSkew1"
invoked from within
"set valSkew [int $valSkew1]..."

Huh? How come it works in the tcl shell, but not my program?
Tom

 
Good question. I have no idea why it works in your interactive shell. My best guess is that somewhere on your system you've got a program called int that does an integer conversion on its command-line argument.

Tcl has no built-in int command. Instead, it has a int() function that's built into the expr command. (Read the expr documentation for a full list of its built-in functions.) Therefore, you need to execute the expr command to run the int() function. A simple modification of your code would be:

Code:
set valSkew1 [expr $what2chk4 * $RATE_SKEW]
set valSkew [expr int($valSkew1)]

A much better modification (unless you also needed that floating-point version of the value) would be to put it all into one command:

Code:
set valSkew [expr int($what2chk4 * $RATE_SKEW)]

You can give expr arbitrarily complex arithmetic expressions to execute. Basically, any math you can do in C, you can do in Tcl using expr. For example:

Code:
set x [expr abs(sin($y + $z)/(3.14-$w))]

Actually, an even better modification is to place the entire arithmetic argument to expr inside of {}. It turns out that expr runs a second round of substitutions on all of its arguments (the reason is fairly subtle and unique to Tcl) -- so the values still get substituted despite the {} quoting -- but the expr parser is able to evaluate the expression far more efficiently. Depending on how complex the expression is, simply quoting with {} can make it run an order of magnitude faster. So, my final suggestion is:

Code:
set valSkew [expr { int($what2chk4 * $RATE_SKEW) }]
- Ken Jones, President
Avia Training and Consulting
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Ken,

Thank you. After I looked at a reply you had made to another thread, I found the link to the wiki website. A solution was in there also which basically mimicked your solution.

Tom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top