-2

I have the following script for calculating the average of the rows of an HTML table:

$(document).ready(function() {
  $('tr').each(function() {
    var count = 0;
    var totmarks = 0;
    $(this).find('.subjects').each(function() {
      var marks = $(this).text();
      if (marks.lenght !== 0) {
        totmarks += parseFloat(marks);
        count += 1;
      }
    });
    $(this).find('#TotMarks').html(totmarks / count);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" style="text-align:center;">
  <thead>
    <tr>
      <th>Student Name</th>
      <th>Math</th>
      <th>Spanish</th>
      <th>Science</th>
      <th>Average</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Pedro</td>
      <td class="subjects">4.0</td>
      <td class="subjects">5.0</td>
      <td class="subjects">6.0</td>
      <td id="TotMarks"></td>
    </tr>
  </tbody>
</table>

Then the average column will display the integer 5 instead of 5.0, is there a solution for this?

double-beep
  • 5,031
  • 17
  • 33
  • 41
  • Does this answer your question? [Formatting a number with exactly two decimals in JavaScript](https://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript) – VLAZ Mar 25 '20 at 06:01

3 Answers3

1

In JavaScript integers are always displayed without decimal point to have the decimal use toFixed(number_of_digits_after_decimal)

so to solve

$(this).find('#TotMarks').html((totmarks/count).toFixed(1));

This will result what you want.

0

Use toFixed() .

The toFixed() method formats a number using fixed-point notation.

$(document).ready(function() {
  $('tr').each(function() {
    var count = 0;
    var totmarks = 0;
    $(this).find('.subjects').each(function() {
      var marks = $(this).text();
      if (marks.lenght !== 0) {
        totmarks += parseFloat(marks);
        count += 1;
      }
    });
    $(this).find('#TotMarks').html((totmarks / count).toFixed(1));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" style="text-align:center;">
  <thead>
    <tr>
      <th>Student Name</th>
      <th>Math</th>
      <th>Spanish</th>
      <th>Science</th>
      <th>Average</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Pedro</td>
      <td class="subjects">4.0</td>
      <td class="subjects">5.0</td>
      <td class="subjects">6.0</td>
      <td id="TotMarks"></td>
    </tr>
  </tbody>
</table>
4b0
  • 21,981
  • 30
  • 95
  • 142
0

Does replacing totmarks/count with (totmarks/count).toLocaleString(undefined, {minimumFractionDigits: 1}) do what you want to accomplish?

See Number.prototype.toLocaleString() for how to format Numbers for display.

Simón
  • 456
  • 8
  • 23