Write the Standard Deviation to a text box (with dynamic numeric scaling)

In this example the script is placed in the button, it returns the Standard Deviation from the resultSet and writes it to a text box

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

if (resultSet.length > 0)
{
    var total = 0.0;
    var count = resultSet.length;

    // ----------------------------
    // Calculate mean
    // ----------------------------
    for (var i = 0; i < count; i++)
    {
        var value = ConvertUtils.stringToNumber(resultSet[i][Alias.MeasureDimension].rawValue);
        total = total + value;
    }

    var mean = total / count;

    // ----------------------------
    // Calculate variance
    // ----------------------------
    var variance = 0.0;

    for (var j = 0; j < count; j++)
    {
        var currentValue = ConvertUtils.stringToNumber(resultSet[j][Alias.MeasureDimension].rawValue);
        var diff = currentValue - mean;
        variance = variance + (diff * diff);
    }

    // ----------------------------
    // Standard Deviation
    // ----------------------------
    var stdDev = Math.sqrt(variance / count);

    // ----------------------------
    // Dynamic scaling
    // ----------------------------
    var absoluteValue = Math.abs(stdDev);
    var scaleSuffix = "";
    var scaledValue = stdDev;

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

    // Round to 1 decimal
    var roundedStdDev = Math.round(scaledValue * 10.0) / 10.0;

    var stdDevText = ConvertUtils.numberToString(roundedStdDev) + scaleSuffix;

    // Output to text widget
    Text_1.applyText("Standard Deviation: " + stdDevText);
}
Code language: JavaScript (javascript)
Scroll to Top