Welcome, guest | Sign In | My Account | Store | Cart

I was in need of a routine to format numbers for a revenue report. I found Andreas Kupries (http://aspn.activestate.com/ASPN/Cookbook/Tcl/Recipe/146220) routine to reformat a number to insert the commas but it didn't address the decimal position alignment. tcl [format] string could format the decimal positions but not insert the commas. So I used Andreas base code and extended it.

Tcl, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
proc format_usd {num {sep ,}} {
    # Find the whole number and decimal (if any)
    set whole [expr int($num)]
    set decimal [expr $num - int($num)]

    #Basically convert decimal to a string
    set decimal [format %0.2f $decimal]

    # If number happens to be a negative, shift over the range positions
    # when we pick up the decimal string part we want to keep
    if { $decimal <=0 } {
        set decimal [string range $decimal 2 4]
    } else {
        set decimal [string range $decimal 1 3]
    }

    # If $decimal is zero, then assign the default value of .00
    # and glue the formatted $decimal to the whole number ($whole)
    if { $decimal == 0} {
        set num $whole.00
    } else {
        set num $whole$decimal
    }

    # Take given number and insert commas every 3 positions
    while {[regsub {^([-+]?\d+)(\d\d\d)} $num "\\1$sep\\2" num]} {}

    # Were done; give the result back
    return $num
}

This recipe does not address a fixed width for the formatted number outside of the decimal position. The neagtive (if any) is placed before the number. Does not place a $ sign before the number

Created by Richard Zimmerman on Thu, 15 Sep 2005 (MIT)
Tcl recipes (162)
Richard Zimmerman's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks