PREP 2015 Question Authoring - Archived

number format control

number format control

by Douglas Young -
Number of replies: 1
I would like to control the number of decimal places webwork uses to do and display calculations. I have the following piece of code:

$vx = non_zero_random(30.0,75.0,0.1);

$vx1 = $vx + $vx*non_zero_random(-0.10,0.10,0.01);

Webwork calculates a value of 53.912 for this. I would like it to round to two decimal places rather than three. This is supposed to be from data found experimentally, and having three decimal places looks like the value is known to an unrealistically high precision.
In reply to Douglas Young

Re: number format control

by Davide Cervone -
I'd say use
    $vx1 = sprintf("%.2f",$vx + $vx*non_zero_random(-0.10,0.10,0.01));
to get the 2 digits that you want. You could alter the display format from the default of "%g" to "%.2f", but the results might be different since you would just be rounding the final answer.

I don't know of a way to force computations to be restricted to a certain number of digits, but you can force intermediate results to 2 digits along the way using sprintf() as above.