I am attempting to write some finance problems and I want the answers to display to two decimal places since they're supposed to represent money. I also want this to happen even when there are trailing zeros (like 21.10). I know I can use

I am attempting to write some finance problems and I want the answers to display to two decimal places since they're supposed to represent money. I also want this to happen even when there are trailing zeros (like 21.10). I know I can use
Have you seen the Currency context? I think it might be a good fit for the problem you are writing. I recommend reading through the documentation so you know all its configuration options.
https://github.com/openwebwork/pg/blob/master/macros/contextCurrency.pl
One option is to set the number format before creating your answers via Compute()
, and then set it back to the default afterward. Since the correct answer is set up by Compute()
at the time it is run, they will have the precision in the number format that you set initially, and then when you set it back, that is what will be used for students.
E.g.,
Context()->{format}{number} = "%.2f"; $answer = Compute(21.1); Context()->{format}{number} = "%g"; BEGIN_PGML 211.00 / 100.00 = [________]{$answer} END_PGML
Will show the student's answers with 6 significant digits, but will give the correct answer as "21.10".
In a situation where you are working with a small numbers of digits, you might want to be sure that your correct answer actually is the same precision as the displayed answer. For example, if you do
Context()->{format}{number} = "%.2f"; $answer = Compute(3.10455); Context()->{format}{number} = "%g";
then the correct answer will show as "3.10", but that will not be accepted as a correct answer with the default tolerances. Even with a relative tolerance of .001 (indicating roughly 3 digits of accuracy), this will still be marked incorrect. So you might want to do something like
Context()->{format}{number} = "%.2f"; $answer = Compute(prfmt(3.10455, "%.2f")); Context()->{format}{number} = "%g";
so that the correct answer will be 3.1 not 3.10455 (due to the prfmt()
), and still be displayed as 3.10 (due to the number format in the context). When you are showing 6 digits, but only requiring 4 (as with the default tolerances and formats), this is not an issue, but if you are showing exactly the number you are looking for, these problems do occur.