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: Beginner:
Formatting numbers

 



jr
Novice

Feb 23, 2000, 1:51 PM

Post #1 of 4 (673 views)
Formatting numbers Can't Post

Okay, so I've written a few scripts and they seem to do what they want, but I am still refining certain techniques...this week's pain is formatting a number in standard number form, such 1,000, 10,000 etc etc rather than 1000 and 10000 etc etc.

I've been looking at sprintf to do it, but I am not quite getting the format correctly, atleast I don't think I am.

I have a few counting statements which count files in a directory...currently the counts are less than 999, but when they increase above that, I'd like them to look like human numbers:
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

opendir THEDIR, "$basepath$key" &#0124; &#0124; die "Unable to open directory: $!";
@allfiles = grep -T, map "$basepath$key/$_", readdir THEDIR;
closedir THEDIR;
$numfiles = @allfiles;</pre><HR></BLOCKQUOTE>

So I am looking for a way to format the variable of $numfiles to 1,000 or 10,000 (etc)...can anyone point me in the right direction?


japhy
Enthusiast

Feb 23, 2000, 5:20 PM

Post #2 of 4 (673 views)
Re: Formatting numbers [In reply to] Can't Post

Perl FAQ 4 has information on how to "commify" numbers, and I offer my own additional solution:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


sub commify {
(my $a = shift) =~ s/\G(\d{1,3})(?=(?:\d\d\d)+(?:\.|$))/$1,/g;
return $a;
}
</pre><HR></BLOCKQUOTE>


jr
Novice

Feb 24, 2000, 8:43 AM

Post #3 of 4 (673 views)
Re: Formatting numbers [In reply to] Can't Post

Well, that isn't working...both fixes (and it was Perl FAQ 5, not 4) result in the same thing:

using a string of:
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

$numfiles2 = 123456789;</pre><HR></BLOCKQUOTE>
with your sub, and also tried it with the FAQ's sub, both spit out the same results for 3 instances they are called from (3 individual results for 3 instances):
740740734
864197523
617283945


japhy
Enthusiast

Feb 24, 2000, 11:49 AM

Post #4 of 4 (673 views)
Re: Formatting numbers [In reply to] Can't Post

D'oh, yes, it was perlfaq5 (files and formats).

Anyway, the function works perfectly for me (Perl 5.005_02).

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


$num = 1234567890.123456;
print commify($num);

sub commify {
(my $a = shift) =~ s/\G(\d{1,3})(?=(?:\d\d\d)+(?:\.|$))/$1,/g;
return $a;
}
</pre><HR></BLOCKQUOTE>

1,234,567,890.123456

[This message has been edited by japhy (edited 02-24-2000).]

 
 


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

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