Moodle 2.6

I am not sure if the number of significant figures can be set in the Formulas question for displaying the value of variables as can be done in the Calculated questions for displaying the answers.

I wrote a variable assignment for the Formulas question, that yields a value retaining only the specified number of significant figures, with the help of the functions abs, floor, log10 and round available in Formulas. Pow(a,b) is used because a^b has another meaning in the Formulas assignments.

The variable assignment is as follows:

nsf=3;

xr=x==0?x: (log10(abs(x))-floor(log10(abs(x)))<log10(2)?round(x*pow(10,nsf-floor(log10(abs(x)))),0)*pow(10,-nsf+floor(log10(abs(x)))):round(x*pow(10,nsf-1-floor(log10(abs(x)))),0)*pow(10,-nsf+1+floor(log10(abs(x)))));

- nsf is the number of significant figures, which can be set to a positive integer value such as 1, 2, 3, 4, etc.;
- x is the variable for which a rounded value is sought;
- xr is the variable that retains only the specified number of significant figures, i.e. the rounded value.

For example, with nsf = 3 and x = 7654.32, the assignment yields xr = 7650. Note that in general x ≠ xr.

If the value of x does not need to be kept, the assignment can be changed to x=x==0?... instead of xr=x==0?.... In this case, x is redefined. In the example, x would become equal to 7650.

The assignment works with any real value of x (positive, negative, greater than one, less than one, not to forget zero) given in decimal or exponential notation. The only thing that the assignment does not do, is assigning significant trailing zeros (with nsf = 3, x = 2.304 is rounded to xr = 2.3, not 2.30).

The first test, log10(abs(x))-floor(log10(abs(x)))<log10(2)?, is used to determine if the first significant digit is "1", in which case the nsf is increased by one. For example, with nsf = 3 and x = 7654.32, the assignment yields xr = 7650, but with x = 1234.56 it yields xr = 1235. In order to have the same precision with a number beginning by 1 as with a number beginning with 9 , it is sometimes recommended to keep one more significant figure when the number begins with 1. For example, with 3 significant figures, 98.9 ± 0.1 has a precision of 0.1/98.9 ≈ 0.001 whereas 102 ± 1 has a precision of 1/102 ≈ 0.01, while 102.3 ± 0.1 has a precision of 0.1/102.3 ≈ 0.001, i.e. the same precision as that of 98.9.

If the same number of significant figures is kept for all numbers, including those beginning by "1", the variable assignment reduces to:

nsf=3;

xr=x==0?x:round(x*pow(10,nsf-1-floor(log10(abs(x)))),0)*pow(10,-nsf+1+floor(log10(abs(x))));

With this last variable assignment and with nsf = 3, x = 98.94 gives xr = 98.9 and x = 102.3 gives 102.