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

my $percent = $answers_correct / 50; $percent = sprintf("%.2f", $percent); print "You scored $percent%";
For some reason this brings back 1.00% instead of 100%. I know I could multiply 50 to have 100 and maybe go about that way but the number of questions may change so I need to find out their percentage from the number right to the number of total questions.

What am I doing wrong?

Replies are listed 'Best First'.
Re: decimal isn't truncating
by jhourcle (Prior) on May 22, 2005 at 11:29 UTC

    A 'percentage' is a ratio that is compared to 100.

    You are creating a ratio that is based on 1, not 100.

    my $ratio_correct = $number_correct / $total_number; my $percent_correct = $number_correct * 100 / $total_number;

    It may also be that you're confused by what '%.2f' does in the context of (s)printf ... From perldoc for sprintf:

    .number "precision": digits after decimal point for floating-point, max length for string, minimum length for integer

    If you're trying to truncate in perl, I'd recommend using '%d', not '%.f' or '%.0f', so it won't round up.

Re: decimal isn't truncating
by dave_the_m (Monsignor) on May 22, 2005 at 08:05 UTC
    my $percent = $answers_correct / 50 * 100;

    Dave.

      Or simply my $percent = $answers_correct * 2;

      :-)