Retrieve the average value from a Resultset and write it to a text box

In this example the script is placed in the button

// Get the result set from the table
var resultSet = Table_1.getDataSource().getResultSet();

if (resultSet.length > 0)
{
    // Variable to store the running total
    var totalValue = 0.0;

    // Loop through each row
    for (var i = 0; i < resultSet.length; i++)
    {
        var currentValue = ConvertUtils.stringToNumber(resultSet[i][Alias.MeasureDimension].rawValue);

        // Add current value to running total
        totalValue = totalValue + currentValue;
    }

    // Calculate the average
    var averageValue = totalValue / resultSet.length;


    // -------- Compact formatting --------

    var absoluteValue = Math.abs(averageValue);

    var scaleSuffix = "";
    var scaledValue = averageValue;

    if (absoluteValue >= 1000000000.0) {
        scaledValue = averageValue / 1000000000.0;
        scaleSuffix = "B";
    }
    else if (absoluteValue >= 1000000.0) {
        scaledValue = averageValue / 1000000.0;
        scaleSuffix = "M";
    }
    else if (absoluteValue >= 1000.0) {
        scaledValue = averageValue / 1000.0;
        scaleSuffix = "K";
    }

    var roundedValue = Math.round(scaledValue * 10.0) / 10.0;

    var formattedTextValue = ConvertUtils.numberToString(roundedValue) + scaleSuffix;

    Text_1.applyText(formattedTextValue);
}
Code language: JavaScript (javascript)
Scroll to Top