Hello everyone,
I’m using the following expressions as levels of attributes in my experiment:
They work perfectly. However, I would like to round the result to the nearest 0.5 or, if that’s not possible in SurveyEngine, at least to the nearest whole number.
For example, if the result is 1.3, I would like it to display as 1.5 instead, or if it is not possible, display 1 instead.
Could you please advise how to refine the code to achieve this?
Thank you in advance for your help.
In your span with class expression you can use (almost) arbitrary Perl code, so this is essentially a Perl question. You can use the int
function to solve your task.
The int
function truncates the decimal digits from a number thereby turning it into an integer. In order to round e.g. $Distance
to the nearest integer you can use int($Distance + 0.5)
. In your example, if $Distance
was 1.3, this would add 0.5 yielding 1.8, then truncate to 1. If $Distance
was 1.6 it would add 0.5 yielding 2.1, then truncate to 2.
In order to round to the nearest .5, you can double the number, then round to the nearest integer, then half the result again, i.e. int(2 * $Distance + 0.5) / 2
. In the example of 1.3, this would give int(2 * 1.3 + 0.5) / 2 = int(3.1) / 2 = 1.5
. In the case of 1.6 it would give int(2 * 1.6 + 0.5) / 2 = int(3.7) / 2 = 1.5
. For 1.8 it would give int(2 * 1.8 + 0.5) / 2 = int(4.1) / 2 = 2
.
CAVEAT: I do not know from the top of my head what int
does with negative numbers, i.e. whether it turns -2.1 into -2 or -3. If you need to support negative numbers you have to check and maybe do a case differentiation based on the sign.