Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Zero Padding to the Right of the Decimal

by jmcnamara (Monsignor)
on Jan 15, 2004 at 16:19 UTC ( [id://321599]=note: print w/replies, xml ) Need Help??


in reply to Zero Padding to the Right of the Decimal


On this line you are converting the number to a string:
$i=sprintf("%3.2f",$i);
But on the following line you convert it back to a number*:
$i=$i+0.1;
So either do the increment before you do the sprintf or else just use printf:
printf "%3.2f\n", $i;

--
John.

* Internally it will be both a number and a string.

Replies are listed 'Best First'.
Re: Re: Zero Padding to the Right of the Decimal
by KPeter0314 (Deacon) on Jan 15, 2004 at 19:09 UTC
    I agree whole-heartedly, the number probably shouldn't be baked into a format until you plan to display it. <insert standard disclaimer about being appropriate for the rest of your script and your coding style>

    So it might look like this with only one print/printf/sprintf:

    my $i=0; while ($i <=100){ $i=$i+0.01; printf("%3.2f\n",$i); }

    -Kurt

      Just one more thing, how about this:

      printf( "%3.2f\n" , ($i + 0.01) );

      Instead of the two lines above?



      ($_='kkvvttuubbooppuuiiffssqqffssmmiibbddllffss')
      =~y~b-v~a-z~s; print
        you'll never exit the loop that way, because you never modify $i.
        You could use +=, though :
        my $i=0; while ($i <=100){ printf("%3.2f\n",$i+=0.01); }
            printf( "%3.2f\n" , ($i + 0.01)  );

        doesn't work.

        Change to:

            printf( "%3.2f\n" , ($i += 0.01)  );

        dave

Log In?
Username:
Password:

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

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

    No recent polls found