SPUG: Dates, anyone?

Ken McGlothlen mcglk at serv.net
Mon Jan 3 21:52:57 CST 2000


"Steve Laybourn" <otter101 at hotmail.com> writes:

| Currency functions! Everyone doing e-commerce programming needs or 
| hand-rolls one of these type of functions, my own of which follows here:
| 
| sub Cur {
| $ix=@_[0];
| $ix=~ s/[^0123456789\.]//g;
| ($ix1,$ix2)=split(/\./,$ix);
| if (length($ix2)==0) { $ix2="00"; }
| if (length($ix2)==1) { $ix2="0"."$ix2"; }
| if (length($ix2)>3) { $ix2=substr($ix2,0,3); $ix2+=5; $ix2=substr($ix2,0,2); 
| }
| $ix3=int(length($ix1)/3);
| $ix4=length($ix1)%3;
| $ix5=substr($ix1,0,$ix4);
| for($ix6=0;$ix6<$ix3;$ix6++) {
|   $ix5.=",".substr($ix1,((3*$ix6)+$ix4+1),((3*$ix6)+$ix4+3)); }
| $final="\$"."$ix5".".$ix2";
| return ($final); }
| 
|    This is somewhat shortened from the original I'd written, but it seems to 
| deal with numbers in a xxxx(...)xxx.xxx(xxx)... format well enough.

I'm afraid to ask what the original was.  Lessee if I have this algorithm
right:

	grab the parameter;
	remove all nonnumeric characters (leaving "." as well);
	split on ".";
	if the last part is zero-length, make it "00", but if it's length 1,
		prepend a zero;
	if it's greater, round it to the nearest cent;
	insert commas in the part before the ".",
	add a dollar sign and return it.

In a word, YUCK, Steve.  That's horrible code.

First of all, learn sprintf.  It's such a handy tool.  Handling the cents bit,
for example (with automatic rounding) is as simple as

	$final = sprintf( "%.2f", $ix );

If you have "3", this turns into "3.00"; if you have "3.149", you get "3.15".

The second part is the commas, and regular expressions are your friend here.
The tricky part is that you have to do it repeatedly for each group of three.
Easily done.

So here's my rewrite of your function:

	sub Cur {
	    my( $ix ) = shift;
	    $ix = sprintf( "%.2f", $ix );
	    1 while $ix =~ s/(.*\d)(\d\d\d)/$1,$2/g;
	    return( "\$$ix" );
	}

Does that help?

							---Ken

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
 Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
 SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
        Email to majordomo at pm.org: ACTION spug-list your_address





More information about the spug-list mailing list