PDA

View Full Version : formatting numbers


sassy_monix
02-06-2005, 11:33 AM
Hi everyone!
Is there a way for me to format numbers in Perl? For example I have the number 1245...I want it to become 1,245. But if the number is 129, it will remain the same.

thanks :)

mlseim
02-06-2005, 09:14 PM
Here's a subroutine I've used before.
The printout comes out as: 4,566,342
==========================================

$num = 4566342;
print "Here's the number: ", comma($num), "\n";

#### subroutine to insert comma(s) ####
sub comma {
local $_ = shift;
1 while s/^(-?\d+)(\d{3})/$1,$2/;
return $_;
}

andyede
02-06-2005, 09:20 PM
just for a difference. this is from the perl cookbook. good book for top snippets of code! I have to admit to using lots of stuff from there instead of figuring it out myself :)

sub commify
{
my$num = reverse $_[0];
$num =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
return scalar reverse $num;
}

mlseim
02-06-2005, 10:38 PM
That's what makes Perl so fun ... there's so many ways to
accomplish the same thing.

Isn't Perl great? :thumbsup: