Welcome to WebmasterWorld Guest from 54.196.68.10

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

Simple PRINTF problem -- extra 0s show up

     
6:35 pm on Jul 22, 2008 (gmt 0)

New User

5+ Year Member

joined:Apr 5, 2008
posts:33
votes: 0


im using this calculator in command prompt:

while(<STDIN>)
{
$i = $_;
chomp($i);
unless($i)
{last}
$o = eval($i);

printf ("the answer is %.3g", $o);
# $o = output answer $i = input
}

if you type 10000/3 you get "the answer is 3.33e+003"

what can i do so that there are no unecessary 0s in the exponent?

[edited by: phranque at 10:17 pm (utc) on July 22, 2008]
[edit reason] disabled smileys ;) [/edit]

8:41 pm on July 22, 2008 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
posts:7999
votes: 0


ACK I totally misunderstood your question.

The correct answer, I believe, is no.

Note that the number of exponent digits in the scientific notation produced by %e, %E, %g and %G for numbers with the modulus of the exponent less than 100 is system-dependent: it may be three or less (zero-padded as necessary). In other words, 1.23 times ten to the 99th may be either "1.23e99" or "1.23e099".

[search.cpan.org...]

(The format arguments for printf are explained in sprintf.)

10:53 pm on July 22, 2008 (gmt 0)

New User

5+ Year Member

joined:Apr 5, 2008
posts:33
votes: 0


thx rocknbil ...
so are you saying there is no way to print "1.23e99" resulting from a perl "eval" function if the system-dependent rule wants to print "1.23e099" ?

and would that mean that the formatting printed locally in the command line window might be different from the formatting printed by a server hosting a web page?

Rudy

10:34 am on July 23, 2008 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Feb 16, 2004
posts:1341
votes: 0


Untested and guessing, but... Maybe if you write the result to a file, then read it back in you could check for zero padding and reformat for the screen (and any printed reports) regardless of the system... in effect defeating the system dependency.

After all, PERL stands for: Practical Extraction (and) Reporting Language

8:31 pm on July 23, 2008 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
posts:7999
votes: 0


Well if you would do that, you could do

$answer = sprintf("%.3g", $o);
$answer =~ s/(.*)(\+[^0]*)(0+)([^0]*)/$1$2$4/;
print "the answer is $answer";

>the answer is 3.33e+3

Directly from sprintf/printf is one thing, treating it as a string is another case altogether. :-)

 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members