Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

by Anonymous Monk
on Oct 24, 2004 at 23:38 UTC ( #402102=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 Anonymous Monk

For integers, one can avoid reverse as well as the repeated substr derivation of the remaining string in the loop:

sub commafy_int { my $n = shift; length($n) > 3 or return $n; my $l = length($n) - 3; my $i = ($l - 1) % 3 + 1; my $x = substr($n,0,$i) . ','; while ( $i < $l ) { $x .= substr($n,$i,3) . ','; $i += 3; } $x . substr($n,$i) }
Not using reverse also makes it much easier to convert this to work on floats (i.e. strings containing a decimal separator, '.'). To do so, simply replace any length calls above with index($n.'.','.').

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 making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2020-10-29 05:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (269 votes). Check out past polls.

    Notices?