This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

string to integer

Help for those learning Tcl or writing their own scripts.
Post Reply
D
Driber
Voice
Posts: 6
Joined: Thu Sep 18, 2008 8:22 am
Contact:

string to integer

Post by Driber »

can someone please post an example of how to convert a string to an integer
Driber.net webmaster
n
nml375
Revered One
Posts: 2860
Joined: Fri Aug 04, 2006 2:09 pm

Post by nml375 »

That would depend on the string in question.. think you could give a couple of examples?
In most cases, scan would be your friend however.

A simple example:

Code: Select all

set string "There are 2 users"
set int [scan $string "There are %d users"
NML_375
D
Driber
Voice
Posts: 6
Joined: Thu Sep 18, 2008 8:22 am
Contact:

Post by Driber »

that's not what I'm looking for

ok here is an example:

I have $str which contains " 4" (that's a whitespace and a number four)

I need that string to be converted to an integer so that I can calculate with it
for example:

Code: Select all

incr str 1
to make it 5


the php equivalent to this would be:

Code: Select all

<?php
$str = " 4";
$num = (int)$str;
?>
Driber.net webmaster
n
nml375
Revered One
Posts: 2860
Joined: Fri Aug 04, 2006 2:09 pm

Post by nml375 »

In this case you might be able to use the expr command. Be aware though that this command may cause some serious security issues if data is not properly sanitized, as all data will be passed through the tcl interpreter.

Of course, scan would still be an option, with a proper pattern...

A third option might be to simply strip the string of spaces using string trim, as tcl will do the necessary type-casting provided the data makes sense (i.e. string looks like an integer if it only contains digits, as a float if it only contains digits and a single dot, and so on).
NML_375
D
Driber
Voice
Posts: 6
Joined: Thu Sep 18, 2008 8:22 am
Contact:

Post by Driber »

I didn't know tcl automatically does type-casting on variables, so I will give string trim a try

thanks
Driber.net webmaster
Post Reply