Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Printing Integer with thousands separator?

Status
Not open for further replies.

miblo

Technical User
Sep 3, 2001
76
SE
This ought to be simple, but I just can't figure it out:

How do I print a large integer with thousands separators? I.e. I want a large integer (for example 65674564376548) to be printed as 65,674,564,376,548.

I'm sure a regexp can do it. The example below works, but it starts from the left, and thus doesn't produce what I want...

$n = 65674564376548;
$n =~ s/([0-9]{3})/$1 /g;

Any tips appreciated.
~Mike
 
There's an example exactly like this in the llama book. I'm not in a position to look it up or even test what's below, but it's something along these lines...

$n = 123456789;
1 while $n =~ s/(\d+)(\d\d\d)/$1,$2/;

Or something like that. As you can see it takes as many digits as it can up until the last three, then inserts a comma...$1 = 123456 $2 = 789 and you get 123456,789
Can't match past the comma next time around, so you get $1=123 $2=456 and wind up with 123,456,789. Can't match enough digits next time through so the "do-nothing" loop exits.

Perl experts? I just read this chapter last night, and of course, I've slept since then...
But Mike, that's the general idea!
 
#!/usr/local/bin/perl
$n = '9876543210';
$n = reverse($n);
$n =~ s/(\d\d\d)/$1,/g;
$n = reverse($n);
print "$n\n";
If you are new to Tek-Tips, please use descriptive titles, check the FAQs,
and beware the evil typo.
 
DumbTech is on the right track,

from Jeffrey Friedl's "Mastering Regular Expressions",
paraphrased to make it operate on '$n',

#!/usr/local/bin/perl
$n = '9876543210';
print"$n\n";
1 while ($n =~ s/^(-?\d+)(\d{3})/$1,$2/);
print"$n\n";

HTH If you are new to Tek-Tips, please use descriptive titles, check the FAQs,
and beware the evil typo.
 
Thanks for all your tips - I now have it working as I wanted.

~Mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top