-2

I made a function in js which calculates the average of 5 numbers and stores it in a variable. for example, if i have the variable
var avg = (0.18 + 0.18 + 0.19 + 0.21 + 1.14)/5;
It gives me this answer : 0.37999999999999995.
I need the length of the answer to be only 3 or 4. Please help me resolve this problem. Thank You!

Kdvinmk
  • 45
  • 1
  • 7
  • `toFixed()` can be used to specify how many numbers after the decimal point should be displayed. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed – Hatted Rooster Sep 26 '14 at 17:52
  • possible duplicate of [Limit the amount of number shown after a decimal place in javascript](http://stackoverflow.com/questions/4256030/limit-the-amount-of-number-shown-after-a-decimal-place-in-javascript) – emerson.marini Sep 26 '14 at 17:52

4 Answers4

3
var avg = (0.18 + 0.18 + 0.19 + 0.21 + 1.14)/5;
avg.toFixed(3);

limits the length to only show 3 numbers after the decimal point.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
0

I'm not sure about what you want to do

To limit the total length with toPrecision(n):

var num = new Number(14.12);
console.log(num.toPrecision(2));//outputs 14
console.log(num.toPrecision(3));//outputs 14.1
console.log(num.toPrecision(4));//outputs 14.12
console.log(num.toPrecision(5));//outputs 14.120

To limit the decimal part, use toFixed(n) :

parseFloat(Math.round(num * 100) / 100).toFixed(2);

The input 1.346 will return 1.35

Benjamin BALET
  • 919
  • 1
  • 11
  • 31
0

I think you need:

parseFloat(avg.toFixed(3));


    var avg = (0.18 + 0.18 + 0.19 + 0.21 + 1.14)/5;
    avg = parseFloat(avg.toFixed(3));
    alert(avg);
mwarren
  • 2,409
  • 1
  • 22
  • 28
-2

EDIT: You can also use .toFixed(n) see Answer below

Greetings,...

Bernd
  • 730
  • 1
  • 5
  • 13