Richard Richard - 5 months ago 29
Javascript Question

jQuery decimals not shown in result sum of checked boxes

The code below make the sum of the checked boxes and shows the result.

I've got this code from this question in stackoverflow.

HTML

<input type="checkbox" checked value="Gez" rel="69.95">Gezichtsbehandeling
<input type="checkbox" value="ExtraLang" rel="9.95">Extra lange
<input type="checkbox" value="Massage" rel="59.95">Massage
<input type="checkbox" value="Pedicure" rel="35">Pedicure

Totaal <span id="output"></span>


JS

<script>
$(document).ready(function() {
function recalculate() {
var sum = 0;

$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
;
});

$("#output").html(sum);
}

$("input[type=checkbox]").change(function() {
recalculate();
});
});

</script>


Problem is that the sum doesn't show decimals.

See here jsfidle

Answer

Per your JSFiddle:

$("input[type=checkbox]:checked").each(function() {
        sum += parseFloat($(this).attr("rel"));
    });

change the parseInt to parseFloat to keep the decimal point.

Working JSFiddle

UPDATE:

Per your request to get the output to be formatted to 2 decimal places.. you need to change

$("#output").html(sum);

To:

$("#output").html(sum.toFixed(2));

That should give you the the format you want.

Working JSFiddle

Comments