Lance Oxley
Lance Oxley

Reputation: 161

JS adding two numbers and displaying to two decimal places

The code I currently have is able to take a number from a text field and do a calculator however I cant get the numbers to display to two decimal places:. Any suggestions on where I can get the toFixed(2) to go:

$(document).ready(function() 
{
    $(".sum").val("0");
    $(".sum1").val("0");
    $(".key").val("");
    function calc() {`
        var $num1 = ($.trim($(".num1").val()) != "" && !isNaN($(".num1").val())) ? parseInt($(".num1").val()) : 0;
        console.log($num1);
        var $num2 = ($.trim($(".num2").val()) != "" && !isNaN($(".num2").val())) ? parseInt($(".num2").val()) : 0;
        console.log($num2);
        $(".sum").val($num1 * 1.05);
        $(".sum1").val($num1 * 1.05-$num1);
    }
    $(".key").keyup(function() {
        calc();
    });
});

Code for form data here.

<form>
<table>
    <tr>
        <td><input type="text" placeholder="Ticket Price" class="num1 key"></td>
    </tr>
    <tr>
       <td> Inc Service Fee:</td><td><input type="text" class="sum" readonly="readonly">
       </td>
    </tr>
    <tr>
       <td><input type="text" class="sum1" readonly="readonly"></td>                          
    </tr>
</form>

Attempting to use toFixed(2) but cant get it to work for the sum and sum1 values.

Thank you for the help.

Upvotes: 3

Views: 73

Answers (1)

palaѕн
palaѕн

Reputation: 73896

You can add toFixed inside calc method like:

function calc() {
   var $num1 = ($.trim($(".num1").val()) != "" && !isNaN($(".num1").val())) ? parseInt($(".num1").val()) : 0;
   console.log($num1);
   var $num2 = ($.trim($(".num2").val()) != "" && !isNaN($(".num2").val())) ? parseInt($(".num2").val()) : 0;
   console.log($num2);

   var sum = parseFloat($num1 * 1.05).toFixed(2)
   var sum1 = parseFloat($num1 * 1.05 - $num1).toFixed(2)

   $(".sum").val(sum);
   $(".sum1").val(sum1);
}

Upvotes: 6

Related Questions