开发者

jquery calculate the sum of products x Quantity

I use this code to calculate the sum : http://jsfiddle.net/QmTNZ/2/

开发者_如何学运维

I want to modify it, to show 0 when there is no valid quantity or it is empty and not "NaN"

I want also to format the Sum to have only 2 numbers after the comma.

Help (I'm beginner in jquery).


Inside your loop, you can check for NaN and replace it with zero:

 if(isNaN(sum)) sum = 0;

For rounding, use this function:

function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

ie,

sum = sum.roundNumber(sum, 2)


You can use the isNaN function to check whether a number is actually a number or not:

if(isNaN(sum)) {
    //Show 0
}
else {
    //Show the value
}

To round the sum to 2 decimal places, you could do something like this:

Math.round(sum * 100) / 100;

Here is an updated fiddle showing how it could work.


demo: http://jsfiddle.net/gN3Te/

$("tr.sum").each(function() {

    var $qnt = $(this).find(".qty");
    var $price = $(this).find("td").eq(1);

    console.log($qnt + " | " + $price);

    var q = $qnt.val();
    if (isNaN($qnt.val()) || $qnt.val() == '') q = 0;

    var sum = parseFloat($price.text()) * parseFloat(q);

    $(this).find("td").eq(2).text(sum.toFixed(2));

    $overall += sum;

});


To format the sum to have two numbers change this:

$(this).find("td").eq(2).text(sum);

to:

$(this).find("td").eq(2).text(sum.toFixed(2));

Then add this

if(isNaN($qnt.val()) || $qnt.val() == "")
            $qnt.val(0);

That will set the quantity to zero if no value exists

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜