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

hello, my question is this: Suppose I have a number: 1.567E-09 I want to round it to two decimal points, but to keep the scale: i.e 1.57E-09 How do I do it without writing a whole subroutine? I tried to use sprintf "%.2f" , but it simply rounded it to 0, which is not what I had in mind. Thanks, and to those who had their Johnson partially severed when they were 8 days old, Hatima Tova.

Replies are listed 'Best First'.
Re: formatting text with E-XX
by shenme (Priest) on Oct 01, 2003 at 12:19 UTC
    What about using something like '%8.3g', just like with C ?   Or even '%8.3G' if you really want the uppercase 'E'.
    perl -e "$f=1.567E-09;printf qq{  '%s'  is  '%8.3g'$/}, $f, $f;"
      '1.567e-009'  is  '1.57e-009'
    
    perl -e "$f=1.567E-09;printf qq{  '%s'  is  '%8.3G'$/}, $f, $f;"
      '1.567e-009'  is  '1.57E-009'
    
    If you need to force only two digits on the exponent you might have to resort to an RE?
Re: formatting text with E-XX
by rinceWind (Monsignor) on Oct 01, 2003 at 12:30 UTC
    I think you want sprintf "%1.2E" which will force scientific notation.

    From perldoc -f sprintf:

    %e a floating-point number, in scientific notation %f a floating-point number, in fixed decimal notation %g a floating-point number, in %e or %f notation ... %E like %e, but using an upper-case "E"
    Hope this helps

    --
    I'm Not Just Another Perl Hacker
Re: formatting text with E-XX
by robartes (Priest) on Oct 01, 2003 at 12:30 UTC
    $ perl -e 'printf("%.3G","1.567E-09")' 1.57E-09

    CU
    Robartes-

Re: formatting text with E-XX
by ambrus (Abbot) on Oct 01, 2003 at 13:37 UTC
    You have to use %g instead of %f. The difference between these is that %f never uses "e", %e always uses it, %g decides from the magnitude of numbers. So, printf "%.3g\n",1.567E-09; works. You need ".3g" instead of ".2" because there are 3 digits together with the one before the point.