views:

74

answers:

3

I have two form inputs which display the calculated invoice subtotal and total of a form.

The problem I'm having is it's not displaying 2 decimal places.

Subtotal function

    function calcProdSubTotal() {

    var prodSubTotal = 0;

    $(".row-total-input").each(function(){

        var valString = $(this).val() || 0;

        prodSubTotal += parseInt(valString);

    });

    $("#product-subtotal").val(prodSubTotal);

};

Total function

function calcOrderTotal() {

    var orderTotal = 0;

    var productSubtotal = $("#product-subtotal").val() || 0;
    var productTax = $("#product-tax").val() || 0;

    var orderTotal = parseInt(productSubtotal) + parseInt(productTax);
    var orderTotalNice = "$" + orderTotal;

    $("#order-total").val(orderTotalNice);

};

How do i go about displaying two decimal places?

+1  A: 

You may want to look here: http://www.mredkj.com/javascript/nfbasic2.html

Basically you can use toFixed(2), but then you get some rounding.

Or, if rounding is bad you can do parseInt(productTax * 100) / 100.

James Black
seems simple enough thanks
Tristan
+1  A: 

If you are working with real numbers it would be better to use parseFloat instead of parseInt. To format the number you could use the toFixed function:

$("#product-subtotal").val(prodSubTotal.toFixed(2));
Darin Dimitrov
thanks looks easy enough
Tristan
+1  A: 

change $("#product-subtotal").val(prodSubTotal);

to $("#product-subtotal").val(addDecimals(prodSubTotal));

and change $("#product-subtotal").val(prodSubTotal);

to $("#product-subtotal").val(addDecimals(prodSubTotal));

function addDecimals(a){
     a += "";
     var i=a.indexOf('.');
    if(i<0){
     return a + ".00";
    }
    var j = a.substring(i);
    console.log(j);
    if(j.length<3){
     for(var k=j.length;k<3;k++)
         a+='0';
     return a;
    } 
    if(j.length>3){
     return a.substring(0, i)+j.substring(0,3);
    }
}
TheVillageIdiot
thanks i'll have a look at it
Tristan