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

I've been using this subroutine for a while to add commas to a number, and truncate the decimal point & remainder. For some reason, it's not working for one of my scripts, while it's working perfectly fine in others. Can anyone see why the following code might not work?
my $testNumber = 123456.789; $testNumber = addComma($testNumber); print $testNumber; sub addComma { my $number = $_[0]; $number = reverse $number; $number =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; $number = reverse $number; return $number; }
returns:
123,456.789

Any help would be greatly appreciated.

Thx, monks!


Steny

Replies are listed 'Best First'.
Re: Problem adding comma & removing decimal
by davido (Cardinal) on Jun 05, 2004 at 05:04 UTC
    sub addComma { my $number = reverse int shift; $number =~ s/(\d{3})(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $number; }

    Partial credit goes to the Perl Cookbook, and the rest to int instead of a RE.


    Dave

      Thx a ton! That works perfectly :-)
      I don't see any significant difference with the code he was using (apart from the int).

      To the OP: I think that if it fails, it's probably to blame to the format of the "numberstring" you're passing to this sub.

        His method was failing for lack of int. That was the significant change. The negative lookahead assertion was rejecting the string when it reached the part of the string that had a decimal point. That caused the substitutions to stop before the string was done being commafied, and did nothing for eliminating the decimal portion.


        Dave