code to comma-delimit numbers

(idea) by Cabaal Tue Aug 01 2000 at 8:43:12
This annoyed me for a good twenty minutes today, so I thought I'd share it...
(This comma-delimits a given number, e.g "12345" becomes "12,345", "1234567" becomes "1,234,567" and so on.)

Tcl:

while {[regsub {^([^,]+)([0-9][0-9][0-9])} $num {\1,\2} num]} {}

PHP:

$a = $b = (string) $num;
while (($b = ereg_replace('^([^,]+)([0-9]{3})', '\1,\2', $a)) && $b != $a) $a = $b;
$num = (string) $a;

P.S.: It was an absolute bitch putting those square brackets in without Everything making it a link. I did it with "[" and "]", for '[' and ']', respectively.
(idea) by Tabs Tue Aug 01 2000 at 9:31:51
Actually, it's slightly easier than that in PHP:

$num = number_format($num,0);
which will turn 1234567 into 1,234,567. You can also specify a character to use instead of a comma, and the amount of decimal places you want, e.g.
$foo = 123;
$foo = number_format($foo,2);
which will give 123.00.
Y'know, if you log in, you can write something here, or contact authors directly on the site. Create a New User if you don't already have an account.