1

Where would I add the toFixed method in this code that calculates an amount so that I can control the decimal to 18 places and so I don't get incorrect calculations.

Right now 100,000 should return 51, but it is returning 51.00000000000004

< script type = "text/javascript" >
  $(document).ready(function() {
    var qty = $("#qty");
    qty.keyup(function() {
      var total = isNaN(parseInt(qty.val() * $("#price").val())) ? 0 : (qty.val() * $("#price").val())
      $("#total").val(total);
    });
  }); 
</script>
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
lupin4
  • 15
  • 9

1 Answers1

1

One option is right here before you set the value:

$("#total").val(total.toFixed(2));

Another option is right here after the math:

(qty.val() * $("#price").val()).toFixed(2)
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • Thanks for that, I need 18 places, so I changed to 18, but the exact values are still coming out different. Now 100,000 is returning 51.000000000000007105, is there a way to keep the 18 places but make sure that exact numbers are returned? – lupin4 Oct 27 '17 at 04:31
  • @DavidClabaugh You're running into the fact that floating point are approximations, and JavaScript numbers not precise enough for that many decimal places. See: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Alexander O'Mara Oct 27 '17 at 04:36