开发者

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

开发者 https://www.devze.com 2023-03-30 09:54 出处:网络
There are standard functions such as atof and atoi in C\'s stdlib.h for converting strings to float开发者_JS百科s / integers (and to do the reverse too). Is there an equivalent of this in Tcl or do I

There are standard functions such as atof and atoi in C's stdlib.h for converting strings to float开发者_JS百科s / 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


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.


One can test string is double $x before using $x in expressions.

E.g., [string is double 1.2.3] returns 0


In my case, this code worked:

set a [string trimleft $a 0] 
0

精彩评论

暂无评论...
验证码 换一张
取 消