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

C stdlib.h has standard functions such as atof and atoi for converting strings to float / integers (and for the opposite, too). Is there an equivalent to this in Tcl or do I need to write my own process to complete these tasks?

+4
source share
5 answers

Everything is a string in Tcl, but functions that expect a number (e.g. expr ) will use this string as an integer:

 % set str " 123 " 123 % set num [expr $str*2] 246 

If you want to format the number in a certain way (for example, create a floating point number with a certain precision), you can use format :

 % set str " 1.234 " 1.234 % set fnum [format "%.2f" $str] 1.23 
+9
source

As already noted, this is all a string in Tcl, so you can just use the given string as a whole or whatever you need. The only caveat is that this should be something that can be interpreted as what you want to use in it (i.e. you can use "a" as an integer)

You can check if something can be interpreted as the desired type using the string is subcommand:

 string is integer "5" ;# true string is integer "a" ;# false string is list "ab cc" ;# true string is list "{ab}c" ;# false 
+2
source

It should also be noted that the equivalents of atof and atoi can be seen as converting the internal Tcl data structures to external binary representations. This is done with the [binary format] command.

+1
source

You can check string is double $x before using the expression $ x in the expressions.

For example, [string is double 1.2.3] returns 0

0
source

In my case, this code worked:

 set a [string trimleft $a 0] 
-2
source

All Articles