homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
Forum Library, Charter, Moderators: coopster & jatar k & phranque

Perl Server Side CGI Scripting Forum

Simple PRINTF problem -- extra 0s show up

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

im using this calculator in command prompt:

$i = $_;
$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 Jul 22, 2008 (gmt 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".


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


 10:53 pm on Jul 22, 2008 (gmt 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?



 10:34 am on Jul 23, 2008 (gmt 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 Jul 23, 2008 (gmt 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. :-)

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved