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!
Asked
Active
Viewed 244 times
-2

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 Answers
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
-
Because otherwise the avg isn't used as STRING and the substring Method don't work. – Bernd Sep 26 '14 at 17:57
-
-
1How fair is that? A totally wrong answer, totally changed (by grabbing someone else's answer) and was accepted. – emerson.marini Sep 26 '14 at 18:25
-
So i upvoted Jameys answer. For Kdvinmk's "correct answer" I can't do anything. – Bernd Sep 26 '14 at 19:26