b310 has asked for the wisdom of the Perl Monks concerning the following question:

Hello:

I'm trying to format some numeric data results to show as dollar values. I've managed to get my to two decimal places. I'm having some trouble trying to figure out how to add commas so the number is easy to read.

Here's the line of code I used to format my data thus far:
my $totalpmt = sprintf("%.2f", $totalpmt);
Is there a simple way to include commas?

Thanks for any help.

Replies are listed 'Best First'.
Re: Formatting Data
by NetWallah (Canon) on May 12, 2004 at 19:03 UTC
    If your code needs to be portable, or be region-friendly, you should use the power of Number::Format, which allows syntax like:
    format_number(1234567.8, 2); # yields '1,234,567.8' format_picture(10002.3, 'USD ##,###.##') ;# yields 'USD 10,002.30'
    among may other options ...

    Offense, like beauty, is in the eye of the beholder, and a fantasy.
    By guaranteeing freedom of expression, the First Amendment also guarntees offense.
Re: Formatting Data
by Nkuvu (Priest) on May 12, 2004 at 17:37 UTC
    Possibly one of these methods will help? (From perldoc perlfaq5) {see update below}:
    How can I output my numbers with commas added? This subroutine will add commas to your number: sub commify { local $_ = shift; 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; return $_; } This regex from Benjamin Goldberg will add commas to numbers: s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g; It is easier to see with comments: s/( ^[-+]? # beginning of number. \d{1,3}? # first digits before first comma (?= # followed by, (but not included in the match +) : (?>(?:\d{3})+) # some positive multiple of three digits. (?!\d) # an *exact* multiple, not x * 3 + 1 or whate +ver. ) | # or: \G\d{3} # after the last group, get three digits (?=\d) # but they have to have more digits after the +m. )/$1,/xg;

    Update: In 352970, tachyon points out that the commify subroutine in the FAQ is pretty inefficient -- "it backtracks to do the job and also chokes on things like $1000 or 'string 123456'." I didn't know this prior to tachyon's post, so I'd suggest using the subroutine from the Perl cookbook (shown in 352970 as well as below in injunjoel's post. Learn something new every day...

Re: Formatting Data
by injunjoel (Priest) on May 12, 2004 at 18:37 UTC
    Greetings all,
    I can't remember now where I found this but it was from someone here... very helpful.
    Thanks whoever it was.
    I Hope this helps.
    sub add_commas { my $text = reverse $_[0]; $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $text; }

    -injunjoel
    Update:
    It's tachyon's code!
    Thanks tachyon!
    Always give credit where credit is due. (original post:352970)
Re: Formatting Data
by NateTut (Deacon) on Mar 27, 2009 at 20:14 UTC
    I always thought sprintf could do this in C.