Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent in Tcl of 'string to X' functions found in C stdlib.h?

Tags:

tcl

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?

like image 431
Ankur Banerjee Avatar asked Dec 22 '22 09:12

Ankur Banerjee


2 Answers

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
like image 90
Lee Netherton Avatar answered May 22 '23 05:05

Lee Netherton


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
like image 24
RHSeeger Avatar answered May 22 '23 05:05

RHSeeger