Home > Net >  javascript code to add 2 digit decimal numbers are rounding off to whole integers
javascript code to add 2 digit decimal numbers are rounding off to whole integers

Time:10-27

Forgive my javascript ignorance - I'm strictly a php developer

function checkTotal() {
  document.listForm.total.value = '';
  var sum = 0;
  var o = 0;
  for (i = 0; i < document.listForm.choice.length; i  ) {
    if (document.listForm.choice[i].checked) {
      sum = sum   parseInt(document.listForm.choice[i].value);
      o  ;
    }
  }
  if (o > 1) {
    sum = sum - 0;
  }
  document.listForm.total.value = sum.toFixed(2);
}
<form name="listForm">
  <input type="checkbox" name="choice" value="10.25" onChange="checkTotal()" />Pizza<br/>
  <input type="checkbox" name="choice" value="9.75" onChange="checkTotal()" />Salad<br/>
  <input type="checkbox" name="choice" value="12.50" onChange="checkTotal()" />Wings<br/> Total:
  <input type="number" size="5" name="total" value="0" />
</form>

The results were 10.00, 9.00 & 12.00 (this does add correctly to 31.00)

should be: 10.25 9.75 12.50 = 32.50

CodePudding user response:

parseInt will parse your string without recognizing a decimal point: by parsing each of your values via parseInt, you're going to wind up dropping the decimal from each one. parseFloat will parse your string into a floating point number, keeping those decimal values around.

 function checkTotal() {
    document.listForm.total.value = '';
    var sum = 0;        var o = 0;
    for (i=0;i<document.listForm.choice.length;i  ) {
      if (document.listForm.choice[i].checked) {
        sum = sum   parseFloat(document.listForm.choice[i].value);
          o  ;
      }
    }
    if (o>1) {sum=sum-0;}
    document.listForm.total.value = sum.toFixed(2);
}

CodePudding user response:

function checkTotal() {
  document.listForm.total.value = '';
  var sum = 0;
  var count = 0;
  // for-of iteration is easier if you don't need index. BTW you forgot "var" in for-i
  for (var ch of document.listForm.choice) {
    if (ch.checked) {
      // as ch.value is properly formatted number, you can use unary " "
      // (or actually any math operator except "a b" cuz it adds strings)
      // ( n), Number(n) and parseFloat(n) are generally equivalent
      sum  = ( ch.value);
      count  ;
    }
  }
  if (count > 1) {
    sum = sum - 0; // why is this, didn't get it
  }
  document.listForm.total.value = sum//.toFixed(2);
}
<form name="listForm">
  <input type="checkbox" name="choice" value="10.25" onChange="checkTotal()" />Pizza<br/>
  <input type="checkbox" name="choice" value="9.75" onChange="checkTotal()" />Salad<br/>
  <input type="checkbox" name="choice" value="12.50" onChange="checkTotal()" />Wings<br/> Total:
  <!--   readonly --!>
  <input type="number" size="5" name="total" value="0" readonly />
</form>

  • Related