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

Takes a number and inserts a comma (or separator of your choice) between every third digit.

Tcl, 4 lines
1
2
3
4
proc comma {num {sep ,}} {
    while {[regsub {^([-+]?\d+)(\d\d\d)} $num "\\1$sep\\2" num]} {}
    return $num
}

Numbers displayed with the appropriate commas are much easier for a person to read. This code is based on an example from the Perl documentation.

1 comment

William Dye 14 years, 2 months ago  # | flag

There's another recipe which does the same thing: http://code.activestate.com/recipes/146220-inserts-thousand-separators-into-a-number/ This recipe was submitted first, but the other one has comments, so I voted the other recipe up instead of this one.

Created by Keith Vetter on Sun, 9 Sep 2001 (MIT)
Tcl recipes (162)
Keith Vetter's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks