Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Eliminating Trailing Zeros

by Anonymous Monk
on Jul 17, 2003 at 14:22 UTC ( #275219=perlquestion: print w/replies, xml ) Need Help??

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

I want to format a real number to 2.4f format. This is simple one would say just use $n=sprintf("%2.4f",$n); , where $n is the number to be rounded. However when I do this I get a number like 23.4600 or 23.0000, which is indeed %2.4f format but I want to eliminate the trailing zeros and decimal where needed resulting in 23.46 and 23

This is a chunk of the code that does it:

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

This does work just fine, however I would like to find away to do the substitution by combining the these 2 separate substitutions into 1 more eloquant one (single line).... or perhaps an even better way to do it all together. Thank you for your help.

Replies are listed 'Best First'.
Re: Eliminating Trailing Zeros
by jmcnamara (Monsignor) on Jul 17, 2003 at 15:18 UTC

    Use the g format instead of f and no further formatting should be required:
    $ perl -e 'printf "%2.4g\n", 23.05' 23.05 $ perl -e 'printf "%2.4g\n", 23.00' 23
    See the sprintf manpage for more details:
    g The double argument is converted in style f or e (or E for G conversions). ... Trailing zeros are removed from the fractional part of the result; ...

    --
    John.

Re: Eliminating Trailing Zeros
by dreadpiratepeter (Priest) on Jul 17, 2003 at 14:29 UTC
    $n =~ s/\.0*$|0*$//;
    UPDATE: fixed lack of reading requirements


    -pete
    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."
      $n=~s/\.|\.0+$//
      That's broken. It deletes the period but leaves in the trailing zeros. This is better, and does what's requested:
      s/\.?0*$//;

      Gary Blackburn
      Trained Killer

      A reply falls below the community's threshold of quality. You may see it by logging in.
      That is Perfect! Thanks!
Re: Eliminating Trailing Zeros
by Aristotle (Chancellor) on Jul 17, 2003 at 15:15 UTC
    For completeness' sake, one that doesn't break when there's no decimal point.
    s/(?:(\.\d*[1-9])|\.)0+\z/$1/;

    Makeshifts last the longest.

Re: Eliminating Trailing Zeros
by ihb (Deacon) on Jul 17, 2003 at 20:16 UTC
        $n += 0;

    KISS,
    ihb

      I can't believe we were all stuck in string mode when the answer was that obvious.

      Makeshifts last the longest.

Re: Eliminating Trailing Zeros
by Lachesis (Friar) on Jul 17, 2003 at 14:36 UTC
    $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
      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)
        
      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."
Re: Eliminating Trailing Zeros
by demerphq (Chancellor) on Jul 17, 2003 at 15:04 UTC
    ($n=sprintf "%2.4f",$n)=~s/\.?0+$//;

    ---
    demerphq

    <Elian> And I do take a kind of perverse pleasure in having an OO assembly language...
Re: Eliminating Trailing Zeros
by RollyGuy (Chaplain) on Jul 17, 2003 at 14:40 UTC
    $n =~ s/\.?0*$//;
    Enjoy.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://275219]
Approved by TStanley
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2020-11-23 22:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?