0

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);
  }
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
afkvision
  • 57
  • 6
  • 1
    try .toFixed(2) ,this could be of some help to you https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed – Geeky Nov 06 '16 at 02:44
  • http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript This might work for you but I'm not entirely sure if this is what you need. – CristianHG Nov 06 '16 at 02:44

1 Answers1

2

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);
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • thanks that seems to work, just one more question, i am having some hoisting issues, i am getting this error: 'average' was used before it was defined – afkvision Nov 06 '16 at 03:17
  • In your code you use `average` before defining it, but it's OK due to hoisting. In my code I don't use `average` before defining it. – Oriol Nov 06 '16 at 03:21