Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Separating big numbers with commas

by Legg83 (Novice)
on Sep 04, 2001 at 23:37 UTC ( #110137=perlquestion: print w/replies, xml ) Need Help??

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

How could I take a big number, and separate it with commas.. like

987654321 = 987,654,321

regardless of how large the number is, i always want to place a comma every three numbers to the left.

Replies are listed 'Best First'.
Re: Separating big numbers with commas
by monkeygirl (Pilgrim) on Sep 04, 2001 at 23:44 UTC

    The Perl Cookbook (Recipe 2.17) has just what you need:

    my $number = 987654321; print commify($number); sub commify { my $text = reverse $_[0]; $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $text }

    Update: blakem is right. And besides, my answer is incomplete. For a more complete answer, look here.

    If Bill Gates can name a company after his "bedroom" problems, I can have a stupid sig that points it out.
      nice one.
Re: Separating big numbers with commas
by blakem (Monsignor) on Sep 04, 2001 at 23:44 UTC
    Try searching for commas in the search bar above... I think the answer has been covered several times before.


Re: Separating big numbers with commas
by John M. Dlugosz (Monsignor) on Sep 05, 2001 at 01:33 UTC
    Don't forget to use the current locale information to determine what the correct separator character is and what positions to group it with.

    In fact, perllocale has an example of doing exactly that!example program that rewrites its command-line parameters as integers correctly formatted in the current locale.

    require 5.004; use POSIX qw(locale_h); # Get some of locale's numeric formatting parameters my ($thousands_sep, $grouping) = @{localeconv()}{'thousands_sep', 'grouping'}; # Apply defaults if values are missing $thousands_sep = ',' unless $thousands_sep; # grouping and mon_grouping are packed lists # of small integers (characters) telling the # grouping (thousand_seps and mon_thousand_seps # being the group dividers) of numbers and # monetary quantities. The integers' meanings: # 255 means no more grouping, 0 means repeat # the previous grouping, 1-254 means use that # as the current grouping. Grouping goes from # right to left (low to high digits). In the # below we cheat slightly by never using anything # else than the first grouping (whatever that is). if ($grouping) { @grouping = unpack("C*", $grouping); } else { @grouping = (3); } # Format command line params for current locale for (@ARGV) { $_ = int; # Chop non-integer part 1 while s/(\d)(\d{$grouping[0]}($|$thousands_sep))/$1$thousands_se +p$2/; print "$_"; } print "\n";
Re: Separating big numbers with commas
by Syrkres (Sexton) on Sep 04, 2001 at 23:52 UTC

    I can help for once! As I found previously!

    $number=1234567; # with commas, should be "1,234,567" $number =~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g;
      How can I embed that into an UNIX Korn shell script? By way of an example here is a perl epoch timestamp conversion used in one of my scripts. LASTUPDATE=$(perl -e '($ss, $mm, $hh, $DD, $MM, $YY) = localtime('${LASTUPDATE}'); printf "%02d\/%02d\/%04d\ %02d\:%02d", $MM +1 , $DD , $YY + 1900, $hh, $mm')
        How can I embed that into an UNIX Korn shell script?
        Can't you sprintf to a variable, comma-munge it, and then print that?
        $x = sprintf "%02d\/%02d\/%04d\ %02d\:%02d", $MM +1 , $DD , $YY + 1900 +, $hh, $mm; $x =~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g; print $x;

        You could lose the interim variable on the way to print, but it's easier to follow as above.

        Quantum Mechanics: The dreams stuff is made of

        I'm not a ksh user, but this script seems to work for me.


        cat ~/.local/bin/commafy #!/usr/bin/perl -nl $_ =~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g; print;


        My usage (to find out that a recent nix build used 18 GB of space):

        $ find /nix/store -cmin -150 | perl -nle '$sum+=-s "$_";END{print $sum +}' | commafy 18,025,136,505

        2018-12-16 Athanasius added code and paragraph tags

      Uh, this doesn't work.
        Looks fine to me....
        #!/usr/bin/perl -wT use strict; my $number='1234567890.01'; # with commas, should be "1,234,567,890.01 +" print "N=$number\n"; $number =~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g; print "N=$number\n";
        N=1234567890.01 N=1,234,567,890.01
        Care to elaborate on which part doesn't work?


Re: Separating big numbers with commas (boo)
by boo_radley (Parson) on Sep 05, 2001 at 22:50 UTC
    update I'm not that special actually. Confession upcoming.

    use Number::Format; my $uuooop = new Number::Format; print $uuooop->format_number("1234567890.0123456789",2);

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://110137]
Approved by root
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2023-12-05 06:10 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (25 votes). Check out past polls.