Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

substitution "0" in decimals

by Sun751 (Beadle)
on Dec 07, 2009 at 23:41 UTC ( [id://811646]=perlquestion: print w/replies, xml ) Need Help??

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

I am wondering if some one can give me a idea,
use strict; use warnings; my $d1 = '1230.1200'; my $d2 = '10332.0120';
How can I write a substitution in perl to get following from above,
$d1 = '1230.12'
and $d2 = '10332.012'
I want to substitute any zero in decimal after digits greater than "0", Any suggestion?

Cheers

Replies are listed 'Best First'.
Re: substitution "0" in decimals
by LanX (Saint) on Dec 07, 2009 at 23:49 UTC
    If you really need to assign strings, you will have to force the scalar into a number afterwards
    DB<1> $d1 = '1230.1200'; DB<2> print $d1 1230.1200 DB<3> print $d1+0 1230.12 DB<4> $d1=$d1+0 DB<5> print $d1 1230.12

    Cheers Rolf

    UPDATE: Please be aware about the limitations of floating-point-numbers as illustrated in the folowing example

    DB<1> $a='0.0000001'; DB<2> print $a+0 1e-07 DB<3> printf "%s",$a 0.0000001 DB<4> $a=sprintf "%s",$a DB<5> print $a 0.0000001 DB<7> $a='0.00000000000000000000000000000000001000000000000000'; DB<8> $a=sprintf "%s",$a+0 DB<9> print $a 1e-35

    If you just wanna reformat a string avoiding any float-representation , you should better consider taking the regex from kennethk's posting!

      Rolf your tricks seems to be easy and very helpful could you please direct me where I can read more about these sort of stuff about perl.
        I don't know which perldoc defines how scalars really work.

        Roughly speaking (my interpretation):

        It's supposed to be transparent if you store a string or a number to a scalar. Operators try an interpretation of operands according to their type.¹

        Storing a number is subject of normalization, since 042.2, 42.20 and 42.2 all represent the same number.²

        But if you store a string by quoting these numbers no information loss is allowed, every zero is a valid character.

        So by reassigning a numeric value ( + is a numerical operator) the number gets normalized.

        Cheers Rolf

        (1) Thats why perl has (at least) 2 flavors for many operators, e.g. eq and == (see Equality Operators) , OTOH Javascript uses + also for concatenation of strings causing many new problems inexistent in perl.

        (2) which may cause new problems, since many dezimal fractions can't be represented as floats w/o a little information loss. (see Re: eq vs ==)

      Be aware though that forcing numericification does lose precision, as .12 cannot be representated by an exact binary representation:
      perl -wE '$d1 = "1230.1200"; $d1 = $d1 + 0; printf "%.20f\n", $d1' 1230.11999999999999999556
      It may not matter for the OP, but at least he should be made aware of when using this trick.
        > It may not matter for the OP, but at least he should be made aware of when using this trick.

        see footnotes in Re^3: substitution "0" in decimals

        Anyway I'm not sure if a conversion to float (resulting in information loss) really happens when stored or just during some numerical calculations:

        DB<4> $d1 = "1230.1200"; DB<5> $d1 = $d1 + 0; DB<6> print $d1."00" 1230.1200

        Cheers Rolf

Re: substitution "0" in decimals
by jettero (Monsignor) on Dec 07, 2009 at 23:50 UTC
    You can use some kind of number formating or you can learn about regular expressions (perlretut). Heck, I think you can even do this with $x = $old + 0. Cheers.

    -Paul

Re: substitution "0" in decimals
by kennethk (Abbot) on Dec 07, 2009 at 23:51 UTC
    Assuming you are only applying this to numbers of the form \d*.?\d* (numerals 0-9 with 0 or 1 decimal point), you can do this fairly simply with the $ metacharacter, which matches the end of a string (Regular Expressions). Your final expression might look like this:

    #!/usr/bin/perl use strict; use warnings; my @numbers = qw(1230.1200 10332.0120 1200); foreach my $number (@numbers) { $number =~ s/(\.\d*?)0*$/$1/ } print join "\n", @numbers;

      This is interesting, but a lot of people try to treat problems as regex problems rather than just doing what they are thinking.

      What you're probably thinking is, "If it has a dot, then remove ending 0's." What you're saying is "replace a dot followed by as few digits as possible, followed by as many zeros as are present, with the part before the zeros." Notice how they aren't the same. That's a code smell for me. And, interestingly, it's slower than doing what you said. Let's try it out. I've provided a micro-optimisation of replacing the * with a + - which means that if there are no zeros, the regex fails, and no substitution is performed, but I have your original (single-splat) still there for comparison. Note that this is likely a premature optimisation, but at the same time, it's so trivial that it's worth making the change. Changing it to the conditional or conditional2 examples would be more drastic based on optimisation alone unless you take my advice to line up your algorithm in your head with the one in your code.

      #!/usr/bin/perl use common::sense; use Benchmark qw(cmpthese); my @N = qw(1230.1200 10332.0120 1200 153.56); cmpthese(-1, { 'single-splat' => sub { my @n = @N; for (@n) { s/(\.\d*?)0*$/$1/; } }, 'single' => sub { my @n = @N; for (@n) { s/(\.\d*?)0+$/$1/; } }, 'conditional' => sub { my @n = @N; for (@n) { s/0+$// if /\./; } }, 'conditional2' => sub { my @n = @N; for (@n) { s/0+$// if /\.\d+$/; } }, });
      And the results on my machine are:
      Rate single-splat single conditional2 conditio +nal single-splat 156392/s -- -25% -43% - +53% single 208524/s 33% -- -24% - +38% conditional2 275692/s 76% 32% -- - +17% conditional 334042/s 114% 60% 21% + --
      That is, your original is the slowest (because I provided a test where yours does a substitution that does nothing while 'single' avoids triggering any modification of the string during the same run), followed by my micro-optimisation (micro? 33% better for these test cases?). The 'conditional' code shows closer to what you're probably thinking, though 'conditional2', which is significantly slower (as it needs to test more of each string), is probably just that tiny bit more accurate (and accuracy beats speed).

        I was certainly aware of the dissonance between the goal of simply stripping zeros and the replacement scheme I used. I was, however, hung up on "Variable length lookbehind not implemented in regex" (i.e. s/0+$(?<=\.\d+)//; or some such other non-functional code).

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-26 05:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found