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 too). Is there an equivalent of this in Tcl or do I need to write my own process for carrying out these tasks?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With