Search code examples
javascripthtmlcurrencydecimalcumulative-sum

How to fix a total to 2 decimal places html/javascript


I have the following javascript code to add checkboxes together when selected and produce a total. What do I need to add to the code to get the total to display 2 decimal places always.

<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 68.50;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) { 
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum;
}
</script>

Solution

  • You just need to call toFixed(n) and pass the number of digits after the decimal point:

    document.listForm.total.value = sum.toFixed(2);