The following examples demonstrate how floating point values can be used within the scripting code we create. All of these examples are implemented in JavaScript . While the same examples might be repeated using several other scripting languages, the syntax might be different. The following simple script assigns floating point values to two variables in order to find their average. This code can be started from any scripting control point. The log file output is " r = 3.85 ".
var a = 5.5; var b = 2.2; var r = (a + b) / 2; task.logmsg("r = " + r);
The next example extends this simple script. Consider that in your input Connector is a multi-valued attribute called "Marks" containing string values (java.lang.String) representing floating point values; a common situation. This attribute is mapped to an attribute in the output Connector called "AverageMark", which holds the average value of all values of the "Marks" attribute. The following code is used in the Advanced Mapping of the "AverageMark" attribute:
// First return the values of the "Marks" attribute var values = work.getAttribute("Marks").getValues(); // Zero out counter and sum variables var sum = 0; var count = 0; // Loop through the values, counting and summing them for (i=0; i<values.length; i++) { // use the Double() function to convert value to number sum = sum + new Number(java.lang.Double(values[i])); count++; } // If count > 0, compute the average var average = (count > 0) ? (sum / count) : 0; // Return the computed average ret.value = average;
The central call in this example is the java.lang.Double(values[i]) used to convert the currently indexed value of "Marks" into a numeric value that can then be used in the average computation.
Parent topic: Java + Script ≠ JavaScript