Sprunkas Sprunkas - 7 months ago 16
Javascript Question

Two digits after comma

I have disabled input field, where result goes ("Kiekis" * "Kaina" = "Suma"), but result in a lot of situations displayed with more than 2 digits (Like 3 * 2.93) even if I used JS toFixed(2) function.

$('#quantity, #price').on('keyup change', function() {
$('#total').val($('#quantity').val() * $('#price').val()).toFixed(2);

Here is all my code in JSFiddle:

Thanks for help in advance! :)


You are attaching events on the input fields before they are loaded on the DOM. So, attach event in parent:

Also toFixed should be inside val, as whatever value is passed in parameter of val function is set as value of that element. So you need to send formatted value in this funciton :


$('div.row').on('keyup change', '#quantity, #price ', function() {
     $('#total').val(($('#quantity').val() * $('#price').val()).toFixed(2));

Updated Fiddle - link