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

Hello, 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 at once.

Replies are listed 'Best First'.
Re: Round numbers?
by moritz (Cardinal) on Nov 04, 2009 at 12:41 UTC
    What do these numbers represent? Your rounding rules seem utterly arbitrary, rounding 0.0205511 to 0.02 introduces an error of 2.8% and preserves only one significant digit, 8.8458e-119 to 8.84e-119 keeps three significant digits (and has an error of only 0.66%), and it's truncating, not rounding.

    Simply chopping digits off numbers is usually a bad idea, because it distorts their meaning.

    Anyway, for formatting you can use printf or sprintf, which you can use to for example to show the first three significant digits.

    Perl 6 - links to (nearly) everything that is Perl 6.
Re: Round numbers?
by cdarke (Prior) on Nov 04, 2009 at 12:47 UTC
    Not so easy, since your spec changes depending on whether you have 'e' (two decimal places) or not (three decimal places). Best I could come up with is:
    printf ((/e/?"%04.2e":"%05.3f")."\n", $number);
    Use sprintf if you wish to convert the number and place into another variable:
    my $var = sprintf ((/e/?"%04.2e":"%05.3f"), $number);


    Update: removed stupid "\n" from sprintf
Re: Round numbers?
by JavaFan (Canon) on Nov 04, 2009 at 12:38 UTC
    s/^([1-9]+[0-9]*\.[0-9][0-9]|0\.0*[1-9][0-9])[0-9]+/$1/
    seems to do the trick.
Re: Round numbers?
by AnomalousMonk (Archbishop) on Nov 04, 2009 at 17:38 UTC