REPORTER 22.1

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;

// Get variable values from template
var value = reporter.currentTemplate.GetVariableValue("VALUE");
var base_value = reporter.currentTemplate.GetVariableValue("VALUE_BASE");

// Check that the variables exist
if (value == null) throw Error("no VALUE variable
");
if (base_value == null) throw Error("no VALUE_BASE variable
");

// Extract numbers from variables
var v = parseFloat(value);
var bv = parseFloat(base_value);

// Check that the variables are valid numbers
if (isNaN(v)) throw Error("VALUE " + value + " is not a valid number
");
if (isNaN(bv)) throw Error("VALUE_BASE " + base_value + " is not a valid number
");

// Check for zero (very small) base value
if (Math.abs(bv) < 1.0e-20)
percent = 100;
else
percent = 100*((v-bv)/bv);

// Create new variable PERCENT
var pvar = new Variable(reporter.currentTemplate, "PERCENT",
"Percent change", percent.toFixed(2));
                   

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 .