Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Answer: How do I add commas to a number?

( #367442=categorized answer: print w/ replies, xml ) Need Help??

Q&A > numbers > How do I add commas to a number? 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 $_; }

Comment on Answer: How do I add commas to a number?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (20)
As of 2015-07-31 16:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (279 votes), past polls