Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

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

by Anonymous Monk
on Oct 24, 2004 at 23:38 UTC ( [id://402102]=note: print w/replies, xml ) Need Help??


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

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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://402102]
help
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found