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

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

by stefp (Vicar)
on Oct 10, 2001 at 05:18 UTC ( [id://117909]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://117909]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-26 00:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found