Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
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 pondering the Monastery: (9)
As of 2014-09-02 06:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (20 votes), past polls