0

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_hidden').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.

2
  • try to do with mapping. and get method. Commented Nov 24, 2010 at 10:48
  • 1
    @steven - .map() returns an array, it really isn't appropriate here, since we're after a single value at the end of the loop. Commented Nov 24, 2010 at 10:52

2 Answers 2

4

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));
}):
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

This is not the place to use it, since the result is a string.
@Nick - could you clarify why you can't use it here; I have tested the result and it appears to work as expected?
You would be adding numbers to strings, the second loop would be a string which doesn't have a .toFixed() method, so it would blow up. You can test it here: jsfiddle.net/nick_craver/TQ7vn
@Nick - thanks for that, I didn't realise the toFixed method changed the type to a string. I have edited my answer appropriately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.