[comp.lang.perl] Printing Numbers with commas in them

kmeek@cti1.UUCP (Kevin Meek) (02/01/91)

Is there an easy way to print numbers formatted with commas that I have 
missed in the manuals?

If not does anyone have a subroutine that will do it in an effective manner?

Thanks 

Kevin.
-- 
Kevin Meek 
kmeek@cti.com

tchrist@convex.COM (Tom Christiansen) (02/01/91)

From the keyboard of kmeek@cti1.UUCP (Kevin Meek):
:Is there an easy way to print numbers formatted with commas that I have 
:missed in the manuals?

Page 233 of the book. :-)  Well, that's for integers.  For floats,
you will wish to futz around a bit.

:If not does anyone have a subroutine that will do it in an effective manner?

As opposed to in an ineffective one? :-)

If $_ contains the number (like 12345678.12), this works:

    1 while s/(.*\d)(\d{3})/$1,$2/;

Note that with floating point numbers, you might get more
than you bargained for unless you do something like  
    $_ = sprintf("%10.2f", $_) 
to discard boring bits.  Without the sprintf you get this:
    12,345,678.11,999,999,918
which you probably don't want.  

Continental notation may be achieved this way:

    s/\./\,/;
    1 while s/(.*\d)(\d{3})/$1.$2/;

--tom
--
"Hey, did you hear Stallman has replaced /vmunix with /vmunix.el?  Now
 he can finally have the whole O/S built-in to his editor like he
 always wanted!" --me (Tom Christiansen <tchrist@convex.com>)

tneff@bfmny0.BFM.COM (Tom Neff) (02/07/91)

In article <1991Feb01.153709.18659@convex.com> tchrist@convex.COM (Tom Christiansen) writes:
>If $_ contains the number (like 12345678.12), this works:
>
>    1 while s/(.*\d)(\d{3})/$1,$2/;
>
>Note that with floating point numbers, you might get more
>than you bargained for ...

I use:

	1 while s/(^[^.]*\d)(\d{3})/$1,$2/;

-- 
Cogito ergo spud.  I think,   O OO   O     Tom Neff
therefore I yam. -- anon       O  OO OO    tneff@bfmny0.BFM.COM

garyp@cognos.UUCP (Gary Puckering) (02/07/91)

In article <389@cti1.UUCP> kmeek@cti1.UUCP (Kevin Meek) writes:
>Is there an easy way to print numbers formatted with commas that I have 
>missed in the manuals?
>
>If not does anyone have a subroutine that will do it in an effective manner?

Picking up on Tom Neff's recent posting, I wrote this for one of my
programs:


sub dollar
{
	local($_) = sprintf("%.2f",$_[0]);
	1 while s/(^[^.]*\d)(\d{3})/$1,$2/;
	$_;
}

This makes it easy to do something like:

	$amount = 12458.62;
	printf ( "Amount = %16s\n",&dollar($amount));

which prints:

   Amount =        12,458.62
	
-- 
Gary Puckering                             Cognos Incorporated
  VOICE: (613) 738-1338 x6100              P.O. Box 9707
  UUCP:  uunet!mitel!cunews!cognos!garyp   Ottawa, Ontario
  INET:  garyp%cognos.uucp@uunet.uu.net    CANADA  K1G 3Z4