CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Frequently Asked Questions:
How can I output my numbers with commas added?

 



Jasmine
Administrator

Jan 26, 2001, 10:15 AM

Post #1 of 1 (1681 views)
How can I output my numbers with commas added? Can't Post

(From the Perl FAQ)

How can I output my numbers with commas added?

This one will do it for you:

Code
    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:

Code
    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:

Code
    # 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;
}


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives