Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Answer: How do I add commas to a number?

by Roy Johnson (Monsignor)
on Jun 16, 2004 at 21:35 UTC ( #367442=categorized answer: print w/replies, xml ) Need Help??

Q&A > numbers > How do I add commas to a number? - Answer contributed by Roy Johnson

A lookaround method that will work on any numbers embedded in a string (but will not commify after a decimal point):
sub commify { local $_ = shift; s{(?<!\d|\.)(\d{4,})} {my $n = $1; $n=~s/(?<=.)(?=(?:.{3})+$)/,/g; $n; }eg; return $_; }
If you prefer the FAQ rule of only working on things that begin with digits or -,
sub commify { local $_ = shift; s{(?:(?<=^)|(?<=^-))(\d{4,})} {my $n = $1; $n=~s/(?<=.)(?=(?:.{3})+$)/,/g; $n; }e; return $_; }
This one does a single pattern match and then uses substr() to insert the commas:
sub commify { local $_ = shift; if (/^-?(\d{4,})/g) { for (my $p=$+[1]; $p>$-[1]; $p-=3) { substr($_,$p,0) = ',' } } return $_; }

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2016-12-11 07:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (168 votes). Check out past polls.