Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I prepared a sub from the FAQs and I can't get it to work. I want to make sure there are 2 decimal points and comma the number in the same subroutine. For some reason, the number isn't coming back accurately.

Alone, each of these work. Together, the number gets jumbled. Any idea as to why?

sub numfix { my $num = shift; 1 while $num =~ s/^([-+]?\d+)(\d{3})/$1,$2/; $num = sprintf("%.2f", $num); return $num; }

Replies are listed 'Best First'.
Re: adding comma and two decimals
by monarch (Priest) on Nov 25, 2005 at 02:16 UTC
    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
      Hi,
      i recommand you to use Number::Format module for better playing with numeric values.
      -kulls
      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!