-2

I am doing average of student marks in jQuery row.append

 row.append($('<TD></TD>').text(((item.Marks1 + item.Marks2 + item.Marks3) / 300) * 100));

I used like this its not working

 row.append($('<TD></TD>').text((Math.floor(item.Marks1 + item.Marks2 + item.Marks3) / 300) * 100));

This is average how to accept two decimals this type of formats please help me.

meena
  • 245
  • 2
  • 12

3 Answers3

0

Use toFixed(2)

 ((item.Marks1 + item.Marks2 + item.Marks3) / 300) * 100).toFixed(2);

DOCS

The toFixed() method converts a number into a string, keeping a specified number of decimals.

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

2 steps that will fix your problem:

  1. A space is not a valid character for a key in Javascript object (assuming that you have something like Marks 1 as key in your object).
    So, you need to replace item.Marks 1 with something like item.Marks1.

  2. Next, convert all of the marks values into Float values:

    parseFloat(item.Marks1)

    So, your code should look like:

row.append($('<TD></TD>').text((Math.floor(parseFloat(item.Marks1) + parseFloat(item.Marks2) + parseFloat(item.Marks3)) / 300) * 100));

EDIT: As suggested by others, you can apply .toFixed(2) at the end of the code line above to get 2 digits after the decimal point.

EDIT2: Added code snippet:

var item = {
  Marks1: 100.10,
  Marks2: 100.105,
  Marks3: 100.201
}


var row = $('table');

var num = parseFloat(item.Marks1) + parseFloat(item.Marks2) + parseFloat(item.Marks3);

num = num / 300 * 100;

num = num.toFixed(2);

row.append($('<TD></TD>').text(num));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
  • I used tried your syntax also but it not showing any values – meena Jan 28 '15 at 06:58
  • @meena Did you make the changes that I suggested to the Javascript object `item` that you are working on? Alternatively, you can try doing `item["Marks 1"]` or `item["Marks1"]`. Let me know if this works. – Rahul Desai Jan 28 '15 at 07:00
  • i edited my question there is no spaces in between marks1 then its fine working @Rahul Desai – meena Jan 28 '15 at 07:02
  • @meena I am glad that my answer helped. Please mark this answer as accepted. Happy to help! – Rahul Desai Jan 28 '15 at 07:03
  • @meena I dont see the point of you using the `Math.floor` and then `.toFixed(2)`. Since you need to get the average, get rid of `Math.floor` and follow EDIT2 in my answer above. – Rahul Desai Jan 28 '15 at 07:19
0

Remove the extra space from that you have in your object item. To access any property you need to use the object name with property without any spaces. e.g, item.Marks1

Use toFixed() to round any value to two decimal places:

In your case:

row.append($('<TD></TD>').text((((item.Marks1 + item.Marks2 + item.Marks3) / 300) * 100).toFixed(2));
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73