in reply to adding comma and two decimals

It was your order of operations. You were trying to perform a sprintf on a number with commas in it (invalid). Try adding the decimal places before adding the commas:
sub numfix { my $num = shift; $num = sprintf("%.2f", $num); 1 while $num =~ s/^([-+]?\d+)(\d{3})/$1,$2/; return $num; } foreach ( qw( 1000 1024 4.3 2.44 1024.44 ) ) { print( $_ ); print( " => " ); print( numfix( $_ ) ); print( "\n" ); }
..prints..
1000 => 1,000.00 1024 => 1,024.00 4.3 => 4.30 2.44 => 2.44 1024.44 => 1,024.44

Replies are listed 'Best First'.
Re^2: adding comma and two decimals
by kulls (Hermit) on Nov 25, 2005 at 04:17 UTC
    Hi,
    i recommand you to use Number::Format module for better playing with numeric values.
    -kulls
Re^2: adding comma and two decimals
by monarch (Priest) on Nov 25, 2005 at 02:18 UTC
    Just as a comment, and it gets said over and over again, but if you had added the line(s)
    use strict; use warnings;
    ..at the top of your code, then you would have received this most helpful warning message:
    Argument "1,000" isn't numeric in sprintf at \ /tmp/deleteme.pl line 9.
      Actually I have that at the top of the script and I didn't recieve a single error anywhere.
      #!/usr/bin/perl use CGI::Carp qw(fatalsToBrowser); use warnings; use strict; use CGI::Cookie; use CGI qw/:standard/; use DB_File;
      Is my script header.

      Thanks for the other suggestion, that worked!