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

Is there a way to print a number, lets say 5e-2, with a specific scieintific notation exponent? For example, I'd like it to print with e-4, so the desired output would be 500e-4. I tried looking on how to do this with printf with no luck.
ysth gave me this great solution:
printf("%.0fe-4\n ",$num*10000)
Thanks.

Replies are listed 'Best First'.
Re: Printing with a Specific Scientific Notation Exponent
by toolic (Bishop) on Sep 18, 2008 at 18:39 UTC
    Update: ikegami++ is right: printf is needed for a more general solution.
    use strict; use warnings; my $exp = -4; my $in = 5e-2; my $out = $in/10**$exp; print "$in --> ${out}e${exp}\n"; __END__ 0.05 --> 500e-4

      Not quite.

      5e-010 --> 5e-006e-4

      Use sprintf '%f' to avoid that problem.

      my $out = sprintf('%f', $in/10**$exp);
Re: Printing with a Specific Scientific Notation Exponent
by broomduster (Priest) on Sep 18, 2008 at 18:47 UTC
    I think you need to roll your own for this. The following will get you started:
    use strict; use warnings; my $num = 0.05; my $num_string = sprintf("%e", $num); print "$num_string\n"; my($mantissa, $exponent) = split /e/, $num_string; my $new_exp = $exponent + 4; my $new_mantissa = $mantissa * 10**$new_exp; print $new_mantissa, "e-04\n"; __DATA__ 5.000000e-02 500e-04
    The right way to do this, of course, is in a subroutine, where you pass in your number along with the desired fixed exponent ('-4' in your example). In that case you need to change the '4' to a variable in the $new_exp calculation. You may also want to use sprintf to format the mantissa for your output (maybe you want 500.0 instead of just 500, for example).

    Updated: You really need

    $new_exp = $exponent - $fixed_exponent;

    if you want to allow for an arbitrary fixed exponent. My example above applies only to negative values of the fixed exponent.

    Never mind. I see now at the end of the OP that ysth supplied a better answer. :-)