Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
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 $_; }

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 scrutinizing the Monastery: (3)
As of 2016-06-26 05:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...











    Results (327 votes). Check out past polls.