Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

How can I output my numbers with commas added?

by faq_monk (Initiate)
on Oct 08, 1999 at 00:23 UTC ( #653=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

This one will do it for you:

    sub commify {
        local $_  = shift;
        1 while s/^(-?\d+)(\d{3})/$1,$2/;
        return $_;
    }

    $n = 23659019423.2331;
    print "GOT: ", commify($n), "\n";

    GOT: 23,659,019,423.2331

You can't just:

    s/^(-?\d+)(\d{3})/$1,$2/g;

because you have to put the comma in and then recalculate your position.

Alternatively, this commifies all numbers in a line regardless of whether they have decimal portions, are preceded by + or -, or whatever:

    # from Andrew Johnson <ajohnson@gpu.srv.ualberta.ca>
    sub commify {
       my $input = shift;
        $input = reverse $input;
        $input =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
        return reverse $input;
    }

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
[marinersk]: That has always been its behavior, but I'm a visual/spacial- awareness guy. When the node disappears, it messes with my head, even though it is on the right margin.
[marinersk]: I was hoping there was a way to turn it on and make it stay on.
[LanX]: what is the intention of your question?
[LanX]: why do you need to see the nodelet without votes left???

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2017-05-29 13:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?