Subject: | New 'formatnum' function (with patch) |
Thought this would be a useful one to add to the mix. Also have a
quicker method for repeat.
*** Util.org 2011-07-28 12:59:04.000000000 -0400
--- Util.pm 2011-07-28 13:56:38.000000000 -0400
***************
*** 35,40 ****
--- 35,44 ----
# remove leading/trailing whitespace
$val = trim($val);
+ # add thousands separators to numbers
+ $val = formatnum($val);
+ $val = formatnum($val, '%.3f');
+
# ensure defined value
$val = define($val);
***************
*** 101,107 ****
push @EXPORT_OK, qw[
crunch htmlesc trim define repeat
unquote no_space fullchomp randcrypt
! jsquote cellfill
];
# the following functions return true or false based on their input
--- 105,111 ----
push @EXPORT_OK, qw[
crunch htmlesc trim define repeat
unquote no_space fullchomp randcrypt
! jsquote cellfill formatnum
];
# the following functions return true or false based on their input
***************
*** 291,296 ****
--- 295,334 ----
#------------------------------------------------------------------------------
+ # formatnum
+ #
+
+ =head2 formatnum(string, sprintf_format)
+
+ Adds commas to a number. Will also optionally format the number with
sprintf()
+ before adding the commas. If commas aren't your thing from that part
of the
+ world, you can set $String::Util::TCHAR with a single character to
represent
+ the thousands separator.
+
+ =cut
+
+ our $TCHAR = ',';
+
+ sub formatnum {
+ my ($num, $format) = @_;
+ $num = sprintf($format, $num) if ($format);
+ $tchar = substr($tchar, 0, 1) || ',';
+
+ # remove potential decimal points out of reformatting
+ my $post = '';
+ ($num, $post) = ($1, $2) if ($num =~ /^(.*?\d)(\D.*)$/);
+
+ $num = reverse($num); # this actually works better in reverse
+ $num =~ s/(\d{3})(?=\d)/$1.$tchar/ge;
+ return reverse($num).$post;
+ }
+ #
+ # formatnum
+
#------------------------------------------------------------------------------
+
+
+
#------------------------------------------------------------------------------
# cellfill
#
***************
*** 431,442 ****
sub repeat {
my ($val, $count) = @_;
! my $rv = '';
!
! foreach (1..$count)
! { $rv .= $val }
!
! return $rv;
}
#
# repeat
--- 469,475 ----
sub repeat {
my ($val, $count) = @_;
! return ($val x int($count));
}
#
# repeat