Math rounding function

  var total = 0;
  for(var i = 0; i < arr.length; i++) {
    total += arr[i]
  }
  return total / arr.length

}

function round(number) {
  return Math.round(total * 100) / 100;

} 
mean([5,8,2,5,8,0,1,4])

The first function will return the average sum, in the case of this array 4.125 but by a decimal place. Any ideas how i can implement the second function to bring the number to a whole number.

The round function you wrote doesn’t even use its argument so won’t do anything really, unless total is a global variable - but that’s probably not what you want.

You have shown you already know of a round function in the standard library, so why not use that?

e.g. return Math.round(total / arr.length);

1 Like

is there a way to implement my argument from the round function so that i still get my desired result?

Something like:

function round(number) {
    return Math.round(number);
}

works, but is redundant obviously. If you want to “hand-roll” a rounding algorithm, I’d probably start with taking a look at the wikipedia article: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero

and taking a look at the various rounding conventions there. I suppose it might be cheating in a sense to use Math.ceil etc, as they are technically a sort of rounding in themselves, but those can be implemented more nicely I guess as seperate functions.

But really, it’s not worth it to go down that rabbit hole

thanks for the explanation!

Im not sure if Im asking it right, but I guess what Im trying to do is use the second function, to round the number that comes from executing the first function, while using Math.round(total * 100) / 100

Not sure if that makes sense :confused:

Are you trying to round to two decimal places?

Imagine 4.125 being rounded with this - Math.round(412.5) is 413 so the whole statement yields 4.13.

To use the function, change Math.round(total * 100) into Math.round(number * 100) - number is the actual argument to the function.

In the first function, instead of returning total / arr.length you can return round(total / arr.length);

to the nearest whole number, in this case, 4

then Math.round is precisely what you want, why do you want to multiply and divide by 100?

  var total = 0;
  for(var i = 0; i < arr.length; i++) {
    total += arr[i]
  }
  return round(total / arr.length)

}

function round(number) {
  return Math.round(number * 100) /100;

}
mean([5,8,2,5,8,0,1,4]) 
4.13

That’s the result I get, but I want it to be 4.0

This line is not doing what you want:
return Math.round(number * 100) /100;

This, as it is written right now, rounds to two decimal places. The function that rounds to zero decimal places is Math.round(number);

See this: https://stackoverflow.com/a/18358056

Reference

Solution for correctly rounding to one:

function roundToOne(num) {    
    return +(Math.round(num + 'e+1')  + 'e-1');
}

This solved the rounding correctly issue for me, hope this helps. :wink:

1 Like