ActiveState Powered by ActiveState

Recipe 68381: Add Commas to a Number


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

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

Discussion

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.

Sign in to comment