in reply to Eliminating Trailing Zeros

$n =~ s/\.?0+$//;
Update: Thanks to dreadpiratepeter for spotting my stupid mistake.
The better option would be $n =~ s/\.\d*?0+$//;
Update2:
That worked with my test data but only because I wasn't using formatted strings so trailing 0s were already dealt with. Doh!
With a %x.yf formatted string the original approach will work fine.
jmcnamara came up with probably the best solution Re: Eliminating Trailing Zeros

Replies are listed 'Best First'.
Re: Re: Eliminating Trailing Zeros
by Anonymous Monk on Jul 17, 2003 at 15:06 UTC
    works except for:
    it doesn't work if you have this:
    (the sprintf before it:

    $n=sprintf("%2.4f",$n); $n =~ s/\.\d*?0+$//;

    What do you think? Is there one that will cover this scenario too?

      Use a sexeger (a reverse regex):
      $n = reverse scalar sprintf("%2.4f",$n); $n =~ s/^0+//g; $n = reverse scalar $n; $n =~ s/\.$//g;
      now if could just condense those two regexes into one ... but sometimes, brute force is better than cleverness.

      UPDATE: aha!

      $n = reverse scalar sprintf("%2.4f",$n); $n =~ s/^0+\.?//g; $n = reverse scalar $n;
      that was easier than i thought ... unless i missed something [And i did ... glad i retested, because i had forgotten to espace the dot .. bad jeffa. Also, the scalar keywords are not necessary].

      And jmcnamara++ ... that's the best solution posted (IMHO) since you already are using sprintf.

      jeffa

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      B--B--B--B--B--B--B--B--
      H---H---H---H---H---H---
      (the triplet paradiddle with high-hat)
      
        An even more fun version:
        $n = reverse scalar sprintf("%2.4f",$n); $n =~ s/\G0//g; $n = reverse scalar $n;
        (Hats off to merlyn's version of this in Effective Perl Programming!)
Re: Re: Eliminating Trailing Zeros
by dreadpiratepeter (Priest) on Jul 17, 2003 at 14:39 UTC
    That turns 420000 into 42

    -pete
    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."