Calculated question type - if-then statement

Calculated question type - if-then statement

by David Feldbaum -
Number of replies: 4

Hello.

Is there any way to have an if-then type of statement in a calculated question formula?  

E.g. I want to ask a question like

"Johnny's allowance is ${X} per week. He already has {Y} amount of $, and he wants to buy a bike that costs ${Z}. If he is already able to buy the bike, then how much money will he have left after the purchase? And if he does not have enough money yet, then how many more weeks does he need to wait before he does?"


The answer should be either  {Y}-{Z}  if  {Y}-{Z} > 0, 

or   ({Z}-{Y}) / {X}   if  {Y}-{Z} < 0.     Is there a way to set this up?

Thank you

Average of ratings: Useful (1)
In reply to David Feldbaum

Re: Calculated question type - if-then statement

by Douglas Broad -

I think so, but you need to make sure that {X}>0.  The formula given should also include some rounding up to a whole number of weeks unless the allowance is given more than once a week.

Something like this should work:

({Y}-{Z})>=0?{Y}-{Z}:({Z}-{Y}) / {X}


A rounding function should be added.

Average of ratings: Useful (1)
In reply to Douglas Broad

Re: Calculated question type - if-then statement

by David Feldbaum -

Thank you very much.

May I ask where did you find the list of these available options ( >= ?  : etc.) I get most of my info from 

https://docs.moodle.org/22/en/Calculated_question_type

and I don't see anything of this sort in there. 

In reply to David Feldbaum

Re: Calculated question type - if-then statement

by Douglas Broad -

Moodle is based on PHP.  This is a PHP shorthand if.  It probably should be in the moodle documents but be careful relying on it.  I wrote a number of questions that use the formulas to do variable text questions and within months, moodle administrators determined that only numbers should be allowable results, breaking all those questions.

Here is a link:

http://davidwalsh.name/php-ternary-examples


An internet search for the terms "shorthand PHP if" should yield more results.

Average of ratings: Useful (1)