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


In reply to Re: Numbers with commas by tachyon
in thread Numbers with commas by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.