in reply to Numbers with commas

Perl doesn't see commas as being part of a number?

Given that it is a string that is less than suprising. In fact Perl tries its best to make a number out of the string - in fact it does find the number 1 (the bit before the first comma).....

C:\>perl -e "print '1,000,000' + 1000" 1001 C:\>

What you see is a warning as Perl knows that effectively doing an atoi()ish thing on a string may give unexpected results. Just remove the commas first and re-add them for output.

sub decommify { my ( $number ) = @_; $number =~ tr/,//d; return $number } sub commify { my ( $number ) = @_; return undef unless $number; ( $number, my $dec ) = $number =~ m!([+-]?\d+)\.?(\d*)!; return undef unless $number; $number =~ s/(\d)(?=(\d{3})+(\D|$))/$1,/g if length($number) > 3; return $dec ? "$number.$dec" : $number; } print commify( decommify("1,000,001.123456789") + 1000 ); __DATA__ 1,001,001.12345679

cheers

tachyon

Replies are listed 'Best First'.
Re: Re: Numbers with commas
by TilRMan (Friar) on May 13, 2004 at 01:48 UTC
    From perlfaq5:
    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 $_; }

      There are a range of variations on the commify theme. That faq version is probably the worst. It is inefficient as it backtracks to do the job and also chokes on things like $1000 or 'string 123456'. The regex in my sub is one of merlyns creations but it chokes on >3 numbers after the decimal point without handling them separately. The Perl cookbook version:

      sub commify { my $text = reverse $_[0]; $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $text; }

      Is more more fault tolerant than the one from the faq.

      cheers

      tachyon

        That faq version is probably the worst.

        Agreed, in general, though there are a range of variations on the "good" theme too.

        The FAQ version is short and doesn't rely on look-ahead. Consequently it is the easiest to copy if you don't care how it works -- and easiest (IMHO) to understand if you do. Short and sweet has significant advantages if you are new to Perl, and that's why it's a good answer to a FAQ.

        I did notice that the cookbook version you quote also appears (more or less) in the FAQ now.