This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

[SOLVED] Add Commas to a Number

Help for those learning Tcl or writing their own scripts.
Post Reply
User avatar
Fire-Fox
Master
Posts: 299
Joined: Sat Sep 23, 2006 9:01 pm
Location: /dev/null

[SOLVED] Add Commas to a Number

Post by Fire-Fox »

Hey!

How do i add commas to a database output so its more readable ? :)
Last edited by Fire-Fox on Wed Feb 29, 2012 12:54 pm, edited 1 time in total.
GreatZ
Fire-Fox | Denmark

Scripts: Relay | Store Text | TvMaze
n
nml375
Revered One
Posts: 2860
Joined: Fri Aug 04, 2006 2:09 pm

Post by nml375 »

I can't think of any packages that will do this for you right now, but then again, the procedure isn't that hard;
Pick out pieces of three digits, and insert the separator of your choice inbetween. The only tricky part is to decide whether the left-most block should be 1, 2, or 3 digits long - as this is determined by the length of the whole string.

Provided you are dealing with integer, the following should probably work:

Code: Select all

proc nFormat {string} {
  set len [expr [string length $string] - 1]
  set i [expr $len % 3]
  set out [string range $string 0 $i]
  while {$i < $len} {
    append out ",[string range $string [incr i] [incr i 2]]"
  }
  return $out
}
If you are dealing with floating-point values, you'd have to separate the decimal part of the value before iterating through the string.
NML_375
User avatar
speechles
Revered One
Posts: 1398
Joined: Sat Aug 26, 2006 10:19 pm
Location: emerald triangle, california (coastal redwoods)

Post by speechles »

There is actually more to it than simply three digits and a comma. What appears to be the best all around answers was..

Code: Select all

proc commify number {regsub -all \\d(?=(\\d{3})+([regexp -inline {\.\d*$} $number]$)) $number {\0,}}
set comma_number [commify "123456128213123412.1234"]

See here: http://wiki.tcl.tk/5000
User avatar
Fire-Fox
Master
Posts: 299
Joined: Sat Sep 23, 2006 9:01 pm
Location: /dev/null

Post by Fire-Fox »

Thanks got i working :D
GreatZ
Fire-Fox | Denmark

Scripts: Relay | Store Text | TvMaze
Post Reply