Pregunta

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>
¿Fue útil?

Solución

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

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

Otros consejos

You can use toFixed() method: http://www.w3schools.com/jsref/jsref_tofixed.asp.

Just create a function:

  function fixedPlace(x) {
    return Number.parseFloat(x).toFixed(2);
  }

And call this function like:

var output = fixedPlace(3.1416);

It will return 3.14

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top