Search code examples
javascriptonkeyup

Why the result onkeyup is different? (Javascript)


I have these codes below to calculate the final score. But when i checked in calculator the result is different. May i know why?

The Code :

function calculate() {
    var a = $("#sc1").val();
    var b = $("#sc2").val();
    var c = $("#sc3").val();
    scavg = (parseInt(a) + parseInt(b) + parseInt(c)) /3;
    scavg = scavg.toFixed(2);
    $("#scavg").val(scavg);
    var d = $("#scavg").val();
    var e = $("#np").val();
    f =  (parseInt(e)*3 + parseInt(d)*7) /10 
    $("input[name=na]").val(f);           
}


Solution

  • parseInt() return integers which are whole numbers. The format of scavg is a float if you want to show decimal numbers to the hundreth (.toFixed(2)), parseFloat() is what you need to use.

    Demo

    function calculate() {
      var a = $("#sc1").val();
      var b = $("#sc2").val();
      var c = $("#sc3").val();
      scavg = (parseFloat(a) + parseFloat(b) + parseFloat(c)) / 3;
      scavg = scavg.toFixed(2);
      $("#scavg").val(scavg);
      var d = $("#scavg").val();
      var e = $("#np").val();
      var f = (parseFloat(e) * 3 + parseFloat(d) * 7) / 10
      $("input[name=na]").val(f);
    }
    
    $('input').on('input', calculate);
    input {
      font: inherit;
      display: block
    }
    <input id='sc1' type='number' step="0.01" placeholder='SC1'>
    <input id='sc2' type='number' step="0.01" placeholder='SC2'>
    <input id='sc3' type='number' step="0.01" placeholder='SC3'>
    <input id='scavg' type='number' step="0.01" placeholder='scAvg'>
    <input id='np' type='number' step="0.01" placeholder='NP'>
    <input name='na' type='number' step="0.01" placeholder='NA'>
    
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>