There are standard functions such as atof
and atoi
in C\'s stdlib.h
for converting strings to floats / integers (and to do the reverse
In my case, this code worked:
set a [string trimleft $a 0]
One can test string is double $x
before using $x in expressions.
E.g., [string is double 1.2.3]
returns 0
As noted, everything is a string in Tcl, so you can just use a given string as an integer or whatever else you need it as. The only caveat being that it needs to be something that can be interpreted as what you want to use it as (ie, you can use "a" as an integer)
You can test to see if something can be interpreted as the type you want using the string is
subcommand:
string is integer "5" ;# true
string is integer "a" ;# false
string is list "a b cc" ;# true
string is list "{a b}c" ;# false
I should note as well that equivatents to atof
and atoi
can be viewed as conversion of internal Tcl data structures to external binary representations. This is done by the [binary format]
command.
Everything is a string in Tcl, but functions that expect a number (like expr
) will use that 'string' as an integer:
% set str " 123 "
123
% set num [expr $str*2]
246
If you want to format a number in a specific way (like producing a floating a point number of a specific precision) then you can use format:
% set str " 1.234 "
1.234
% set fnum [format "%.2f" $str]
1.23