http://qs321.pair.com?node_id=117909


in reply to How do I print a large integer with thousands separators?

$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));