| View previous topic :: View next topic |
| Author |
Message |
Fire-Fox Master

Joined: 23 Sep 2006 Posts: 270 Location: /dev/null
|
Posted: Tue Feb 28, 2012 2:06 pm Post subject: [SOLVED] Add Commas to a Number |
|
|
Hey!
How do i add commas to a database output so its more readable ?  _________________ GreatZ
Fire-Fox | Denmark
Scripts: Relay | Store Text | TvMaze
Last edited by Fire-Fox on Wed Feb 29, 2012 12:54 pm; edited 1 time in total |
|
| Back to top |
|
 |
nml375 Revered One
Joined: 04 Aug 2006 Posts: 2857
|
Posted: Tue Feb 28, 2012 6:33 pm Post subject: |
|
|
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: | 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, idling at #eggdrop@IrcNET |
|
| Back to top |
|
 |
speechles Revered One

Joined: 26 Aug 2006 Posts: 1398 Location: emerald triangle, california (coastal redwoods)
|
Posted: Tue Feb 28, 2012 9:02 pm Post subject: |
|
|
There is actually more to it than simply three digits and a comma. What appears to be the best all around answers was..
| Code: | | 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 _________________ speechles' eggdrop tcl archive |
|
| Back to top |
|
 |
Fire-Fox Master

Joined: 23 Sep 2006 Posts: 270 Location: /dev/null
|
Posted: Wed Feb 29, 2012 12:15 pm Post subject: |
|
|
Thanks got i working  _________________ GreatZ
Fire-Fox | Denmark
Scripts: Relay | Store Text | TvMaze |
|
| Back to top |
|
 |
|