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

Hello monks, I have a list of numbers that can be in format like:
8.8458e-119 1.06542e-52 2.68e-36 2.91405e-35 0.0190644 0.0205511 0.004
Is there something you can suggest me that I use to have some more "elegance" appearance, i.e:
8.84e-119 1.06e-52 2.68e-36 2.91e-35 0.019 0.02 0.004
? Note that I have all these number formats and I want to use a command that could apply to all of them. I tried using:
$rounded = sprintf("%.3f", $number);
, but it returns all 0 (which is natural of course)... So, can I use something else?

Replies are listed 'Best First'.
Re: Round numbers?
by AnomalousMonk (Archbishop) on Oct 01, 2009 at 23:28 UTC
    See sprintf  %g format specifier:
    >perl -wMstrict -le "my @nra = ( 8.8458e-119, 1.06542e-52, 2.68e-36, 2.91405e-35, 0.0190644, 0.0205511, 0.004, ); for my $n (@nra) { my $fmt = $n > 0.001 ? '%5.2g' : '%5.3g'; printf qq{$fmt \n}, $n; } " 8.85e-119 1.07e-052 2.68e-036 2.91e-035 0.019 0.021 0.004
    Update: This loop produces the same output without needing an intermediate variable:
    printf qq{%5.*g \n}, $_ > 0.001 ? 2 : 3, $_ for @nra;
      Because I am new to Perl and don't understand it that much, can you please tell me how these lines interpret?
      for my $n (@nra) { my $fmt = $n > 0.001 ? '%5.2g' : '%5.3g'; printf qq{$fmt \n}, $n; }

      It's like:
      for my $n (@nra) { my $fmt=$n; if($n>0.001){ ????? } else { ?????? } printf qq{$fmt \n}, $n; }

      Thank you for your time!
        No, like:
        for my $n (@nra) { my $fmt; if ($n > 0.001){ $fmt = '%5.2g'; } else { $fmt = '%5.3g'; } printf qq{$fmt \n}, $n; }
        See Conditional Operator in perlop.

        Note that
            $x = $y > $z ? 'foo' : 'bar';
        is perhaps more clearly written as
            $x = ($y > $z) ? 'foo' : 'bar';