开发者

javascript jquery .each() problem

开发者 https://www.devze.com 2023-01-27 05:42 出处:网络
I have some form input elements with class .commission_plan and different IDs. I need to sum up this element\'s values. I use this code:

I have some form input elements with class .commission_plan and different IDs. I need to sum up this element's values. I use this code:

jQuery(document).ready(function() {
    var total = 0;
    $('.commission_plan').each(function() {
        total = total + parseFloat($(this).val());
    });
    $('#payment_total_amount_hi开发者_JAVA百科dden').val(total);
    $('#payment_total_amount').text('Total: ' + total);
}):

In my input fields are the values 3.45 and 4.65. But why does #payment_total_amount contain 8.100000000000001? Very strange behavior.


This is just how floating point math behaves, for currency situations you often want 2 decimal places, so use .toFixed(2) when rendering it, like this:

var total = 0;
    $('.commission_plan').each(function(){
        total = total + parseFloat($(this).val());
    });
    $('#payment_total_amount_hidden').val(total.toFixed(2));
    $('#payment_total_amount').text('Total: '+total.toFixed(2));
}):


This is the result of precision issues with floating point values. You could try using the toFixed(n) javascript method to limit the number of decimal places.

Edit: As clarified by Nick in the comments the toFixed(n) method will convert a float to a string so it should only be used once the calculation is complete.

0

精彩评论

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