Version 12 of format

Updated 2005-02-15 08:45:39

format - Format a string in the style of sprintf

 format formatString ?arg arg ...?  

This command generates a formatted string in the same way as the ANSI C sprintf procedure (it uses sprintf in its implementation). FormatString indicates how to format the result, using % conversion specifiers as in sprintf, and the additional arguments, if any, provide values to be substituted into the result. The return value from format is the formatted string.

More at: http://purl.org/tcl/home/man/tcl8.4/TclCmd/format.htm


Tips and Tricks with format

You can use [format] to produce unsigned integers for display (but don't reckon with them - for expr they're still signed!):

 % format %u -1
 4294967295

See floating-point formatting for discussion on how to write format strings to handle floats...


To make numbers look nice:

 set fah [format "%0.2f" [expr $temperature_cel * 9 / 5 + 32]]

Color formatting:

 set color [format #%02x%02x%02x $r $g $b]

A limited formatting of decimals to characters is available in other languages, e.g. CHR() in Basic. If you use that more often, here's a cute shortcut:

 interp alias {} chr {} format %c
 % set a [chr 49][chr 48]
 10

See Narrow formatting for short rendering of big integers, with powers of 1024:

 % fixform 12345678
 11.7M

this method should get format string and explain the format structure. this is a fast scatch.

 proc explainFormat {formatStr} {
 set index 1
 foreach frm [split $formatstr "%"] {
        set extra ""
        set size 0
        regexp {([0-9]+)([duioxXcsfegG])(.*)} $frm => size type extra
        if {$size==0} {
                set size [string length $frm]
        } else {
                set frm "%$size$type"
                set size [string trimleft $size 0]
        }
        for {set i 0} {$i<2} {incr i} {
                set newIndex [expr {$size +$index -1}]
                puts "$index-$newIndex '$frm'"
                set index [expr {$newIndex +1}]
                if {$extra==""} {
                        break
                } else {
                        set frm $extra
                        set size [string length $extra]
                }
        }
 }
 }

%explainFormat hello%02s000%3d

1-5 'hello'

6-7 '%02s'

8-10 '000'

11-13 '%3d'


Tcl syntax help - Arts and crafts of Tcl-Tk programming - Category Command