Doran L
Doran L

Reputation: 299

javascript unable to use double to get total sum

I have a javascript below which calculate the sum from the checkbox value but i can't seem to get to output as double value. Currently I left it as 0 as I tested with 0.00 and it also doesn't work

For example: 8.20 + 12.70 = 20.000999999999998

 echo "\t<div class='item'>
            <span class='CDTitle'>{$CD['CDTitle']}</span>
            <span class='CDYear'>{$CD['CDYear']}</span>
            <span class='catDesc'>{$CD['catDesc']}</span>
            <span class='CDPrice'>{$CD['CDPrice']}</span>
            <span class='chosen'><input type='checkbox' name='CD[]' title='{$CD['CDID']}' value='{$CD['CDPrice']}' /></span>
        </div>\n";  

JS:

var sum=0;
$(document).on("click",".chosen",function() {
    var chk=$(this).find("input");
    if(chk.is(':checked')) {
        sum = sum + parseInt(chk.val());
    } else {
        sum = sum - parseInt(chk.val());
    }
    $('#total').val(sum);

Upvotes: 1

Views: 359

Answers (1)

L Ja
L Ja

Reputation: 1506

Your problem is that you're parsing your values as integers. An integer can't have decimal values. You need to use parseFloat() instead.

Upvotes: 7

Related Questions