sal - 1 year ago 73

Javascript Question

I tried nearly everything but cant seem to get the final result as a round number up to 2 decimal digits. It's a standard deviation

Thank you in advance, here is the code.

`function round(number) {`

var final = Math.round(number * 100) / 100;

return final;

}

function stdev(arr) {

var avg = average(arr);

var squareDiff = arr.map(function(arr) {

var diff = arr - avg;

var sqrDiff = diff * diff;

return sqrDiff;

});

var avgSquareDiff = average(squareDiff);

var stdDev = Math.sqrt(avgSquareDiff);

return stdDev;

function average(data) {

var sum = data.reduce(function(sum, arr) {

return sum + arr;

}, 0);

return round(sum / data.length);

}

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You round the value when you return in `average`

.

However, in `stdev`

, then you calculate the square root of that rounded value.

That operation will most likely return a number with lots of decimals, and you return it directly without rounding it again.

Most probably you need

```
function round(number) {
var final = Math.round(number * 100) / 100;
return final;
}
function average(data) {
var sum = data.reduce(function(sum, arr) {
return sum + arr;
}, 0);
return sum / data.length;
}
function stdev(arr) {
var avg = average(arr);
var squareDiff = arr.map(function(arr) {
var diff = arr - avg;
var sqrDiff = diff * diff;
return sqrDiff;
});
var avgSquareDiff = average(squareDiff);
var stdDev = Math.sqrt(avgSquareDiff);
return round(stdDev);
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**