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

Hi monks, I wondered if any one could tell me how to print a number to 2 decimal places. I know how to round off a number using 'int' but can't do the 2 d.p.
my $percent = int (($amount / $length) * 100);
cheers!

Replies are listed 'Best First'.
Re: decimal places
by rasta (Hermit) on Jan 17, 2003 at 10:18 UTC
    Perl has printf(). And so you may use of advantage of the following:
    printf "%.2f\n", $percent;
    Updated: Currected mixed up decimal places with decimal digits.

    -- Yuriy Syrota
      you could use sprintf:
      my $percent = sprintf ("$.2f",100*$amount / $length);
      that way the variable $percent contains the rounded result
Re: Decimal Places
by tadman (Prior) on Jan 17, 2003 at 10:42 UTC
    I think rasta was on the right path, but then took a left turn at the last second, as "%2d" formats to two digits, not two decimal places.
    my $percent = sprintf("%.2f", ($amount * 100 / $length));
    Where printf prints out the result, sprintf will return the result without printing, or in another sense, print to a string.
Re: decimal places
by Arien (Pilgrim) on Jan 17, 2003 at 10:23 UTC
    I know how to round off a number using 'int'

    I know how to round not using int. ;-) int just truncates, which isn't rounding half the time.

    Check Perl FAQ 4 or use perldoc -q round for more info.

    — Arien