This is a wonderful little Perl script which is very useful when dealing with monetary database output.

sub docurr($){
local($_)=shift;
$_=sprintf("%.2f",$_);
1 while s/(.*\d)(\d\d\d)/$1,$2/;
$_="\$".$_;
$_;
}


This code is a procedure which takes in one variable"$_" and makes it a float with 2 decimal places using sprintf. Next, The codelooks for an ending of 4 numbers and places a comma in the appropriate position. It continues working its way up the variable one character at a time adding commas when there is a pattern match. When no more pattern matches occur, we cat the results of our while loop with a dollar sign and return the resulting string.

syntax: $printme=&docurr($somenumber);
Of course, this code is very locale-specific. For one thing, what if the current locale uses `,' instead of `.' as the decimal separator? Then inserting commas as period separators is not a good idea. Also, what if the currency symbol is not `$'? Of course, C-style locales have their own problems; see, for example, the SECURITY section of the perllocale(1) manpage.

In addition, it loses accuracy. You don't always want to lose the ability to represent fractions of cents.

Log in or register to write something here or to contact authors.