Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Re: Eliminating Trailing Zeros

by Anonymous Monk
on Jul 17, 2003 at 15:06 UTC ( [id://275238]=note: print w/replies, xml ) Need Help??


in reply to Re: Eliminating Trailing Zeros
in thread 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?

Replies are listed 'Best First'.
(jeffa) 3Re: Eliminating Trailing Zeros
by jeffa (Bishop) on Jul 17, 2003 at 15:19 UTC
    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!)
        This brings up a very good point - oftentimes it's better, both coding- and performance-wise, to use reverse when handling strings than it is to try and work from the end. For example, when trying to handle group separators locale-independently for formatting numbers, the easiest way is to:
        my $g = ","; # Could be ' ' or '.' in other locales my $n = 1234567890; $n = reverse $n; $n =~ s/(\d{3})/\1$g/g; $n = reverse $n;
        Much better than the options without reverse.

        ------
        We are the carpenters and bricklayers of the Information Age.

        Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

        Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://275238]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-19 19:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found