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

Answer: How do I print a large integer with thousands separators?

by stefp (Vicar)
on Oct 10, 2001 at 05:18 UTC ( #117909=categorized answer: print w/replies, xml ) Need Help??

Q&A > data formatting > How do I print a large integer with thousands separators? - Answer contributed by stefp

$number =~ s/(\d{1,3}?)(?=(\d{3})+$)/$1,/g;

The lookahead (?=(\d{3})+$) ensures that the number of digits before each underscore we insert is a multiple of 3.

An extra set of parentheses fools Perl because the regex parser barks when there are two quantifiers in a row, which is perfectly legitimate here.

This issue was also discussed in the thread Splitting every 3 digits?.

Replies are listed 'Best First'.
Re: Answer: How do I print a large integer with thousands separators?
by Roy Johnson (Monsignor) on Jan 09, 2004 at 22:20 UTC
    To do it without capturing and resubstituting, you can add a lookbehind:
    s/(?<=\d)(?=(?:\d{3})+\b)/$sep/g;
    This also works:
    substr($n, pos($n), 0) = $sep while ($n =~ /\d(?=(?:\d{3})+\b)/g);
    As does:
    substr($n, -($_*3 + ($_-1)*length($sep)), 0) = $sep for (1..int((lengt +h($n)-1)/3));
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 drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2020-10-29 05:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (269 votes). Check out past polls.

    Notices?