Example : 1 Percent Change in Two Values
Example 1: Percent change in two values
Problem
Take two input variables VALUE and VALUE_BASE
Calculate new variable PERCENT = 100*(VALUE - VALUE_BASE) / VALUE_BASE)
Check if VALUE_BASE=0 and if so don't do the division but set PERCENT
to 100
Solution
JavaScript |
var percent; |
Discussion
Variables in REPORTER are stored in each template so to get the values of the variables VALUE and VALUE_BASE we need to get the template that we are using. The easiest way to do this is to use the currentTemplate property of the reporter object that is created when REPORTER starts. Once we have the template there is a method GetVariableValue that allows us to get a variable value.
GetVariableValue returns the value of the variable as a string or null is the variable does not exist. We can easily check for this and terminate with an error if the variable is missing.
We want to get the numerical values of the variables and check if they are valid numbers. The standard JavaScript functions parseFloat() and isNaN() allow us to do this.
To check if the value is zero (or very small) we use the standard Math.abs() function and calculate a value accordingly.
To create a new variable we use the Variable constructor. This takes the template, the variable name, description and value as arguments. Finally, maths in JavaScript is performed in double precision so the value we calculated will be given to many significant figures. We are not interested in this so we use the standard Number.toFixed() function to limit the number of decimal places to 2.
The source code for this example is available here .