Problem in number summation with Javascript

Asked

Viewed 11 times

0

I have 3 fields that I must add the value and present them in the total field, but when performing the sum Javascript is only concatenating the values

Sum function:

function calculateTotal(){
    var totalAmount = 0; 
    $("[id^='painting_']").each(function() {
        var id = $(this).attr('id');
        id = id.replace("painting_",'');
        var painting = $('#painting_'+id).val();
        var spares  = $('#spares_'+id).val();
        if(!spares) {
            spares = 0;
        }
        var labour  = $('#labour_'+id).val();
        if(!labour) {
            labour = 0;
        }
        var total=0;
        total = parseFloat(spares+labour+painting);
        $('#total_'+id).val(parseFloat(total));
        totalAmount += total;       
    }); 
    $('#subTotal').val(parseFloat(totalAmount));    
    var taxRate = $("#taxRate").val();
    var subTotal = $('#subTotal').val();    
    if(subTotal) {
        var taxAmount = subTotal*taxRate/100;
        $('#taxAmount').val(taxAmount);
        subTotal = parseFloat(subTotal)+parseFloat(taxAmount);
        $('#totalAftertax').val(parseFloat(subTotal));      
        var totalAftertax = $("#totalAftertax").val();
        $('#amountDue').val(totalAftertax);
    }
}
  • probably the problem is on that line: total = parseFloat(spares+labour+painting); is concatenating and then converting to float, should convert to numbers before adding

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.