Gossamer Forum
Home : General : Perl Programming :

Formating currency

Quote Reply
Formating currency
Can somebody help me with perl code to format a number into "999,999.99"

Say I have a price field in my product database in the form of "999999.99" that I can manipulate with sum, multiply and so on.

And after manipulation, I want to display it in the "999,999.99" format.

Any help is highly appreciated.


[This message has been edited by S4Nugi (edited March 14, 1999).]
Quote Reply
Re: Formating currency In reply to
Hi,

Give this a shot:

Code:
sub commify {
local $_ = shift;
$_ = sprintf ("%.2f", $_); # 2 decimal points.
1 while s/^([-+]?\d+)(\d{3})/$1,$2/; # insert commas
return $_;
}
Quote Reply
Re: Formating currency In reply to
Cool! It works smoothly.

Thanks a lot Alex!

Maybe you can explain the line
"1 while s/^([-+]?\d+)(\d{3})/$1,$2/;"

Thanks again.
Quote Reply
Re: Formating currency In reply to
 
Quote:
Maybe you can explain the line
"1 while s/^([-+]?\d+)(\d{3})/$1,$2/;"

That's taken from the Perl FAQ:

http://language.perl.com/...tput_my_numbers_with

Basically what it does is repeatedly loops over the input and grabs the last three numbers and sticks a comma before them. So given the input 1234567 it would do this:

1234567 => 1234,567 # first pass
1234,567 => 1,234,567 # second pass
1,234,567 => can't match so quits.

and then it would stop. The [-+]? just allows for a + or - sign to be at the beginning.

Cheers,

Alex