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

后端 未结 5 1431
南旧
南旧 2021-01-19 17:50

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

相关标签:
5条回答
  • 2021-01-19 18:26

    In my case, this code worked:

    set a [string trimleft $a 0] 
    
    0 讨论(0)
  • 2021-01-19 18:28

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

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

    0 讨论(0)
  • 2021-01-19 18:28

    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
    
    0 讨论(0)
  • 2021-01-19 18:43

    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.

    0 讨论(0)
  • 2021-01-19 18:45

    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
    
    0 讨论(0)
提交回复
热议问题