APM: Question: breaking up a numeric variable
Marc Majcher
majcher at majcher.com
Thu Sep 26 13:47:04 CDT 2002
"Goldilox" <Goldilox at teachnet.edb.utexas.edu>:
:
:Is there a good way to take a numeric variable of undetermined length
:and print it out with a comma appropriately placed at every third character
:slot from the end
:
'perldoc -q comma' gives us this:
Found in /usr/local/lib/perl5/5.6.1/pod/perlfaq5.pod
How can I output my numbers with commas added?
This one will do it for you:
sub commify {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}
$n = 23659019423.2331;
print "GOT: ", commify($n), "\n";
GOT: 23,659,019,423.2331
You can't just:
s/^([-+]?\d+)(\d{3})/$1,$2/g;
because you have to put the comma in and then recalculate
your position.
Alternatively, this code commifies all numbers in a line
regardless of whether they have decimal portions, are
preceded by + or -, or whatever:
# from Andrew Johnson <ajohnson at gpu.srv.ualberta.ca>
sub commify {
my $input = shift;
$input = reverse $input;
$input =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
return scalar reverse $input;
}
--
DVS
Patriotism is voluntary.
More information about the Austin
mailing list