lupin4
lupin4

Reputation: 15

Controlling the decimal output in JavaScript

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>

Upvotes: 1

Views: 42

Answers (1)

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60517

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)

Upvotes: 1

Related Questions