For example I have the following HTML:
<div class="result">
<div class="score">3.55</div>
<div class="score">4.50</div>
<div class="score">4.50</div>
<div class="score">4.20</div>
<div class="score">4</div>
</div>
<div class="result">
<div class="score"5>2.33</div>
</div>
With jquery I count all "score divs", for each "result div" and create for each "result div" a new div with the result of it, called "goal".
My function:
$('.result').each(function () {
var sum = 0;
$(this).find('.score').each(function () {
sum += Number($(this).text() / 5);
});
$(this).append('<div class="goal">' + sum + '</div>');
});
My problem
I want to show only one number after the comma. I try to integrate ".toFixed(1);", but it always fails.
Something like this:
sum += (Number($(this).text() / 5)).toFixed(1);
The result of this try is an endless, wrong number ...
How will it work?
Since / 5
already casts to a number, you don't need Number(...)
around that part at all. Just sum += $(this).text() / 5;
will do. Unless you're pedantic, in which case sum += parseFloat($(this).text()) / 5;
is what you need.
That aside, you should always work on "exact" numbers, and only apply rounding at the very end. So '<div class="goal">' + sum.toFixed(1) + '</div>';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.