3

I'm trying to add together decimal numbers but when i alert the variable finalnumber i get zero. The variable number is a decimal number. How do i solve this so that variable finalnumber is the sum of all number?

var finalnumber = 0;

$('#chosen-keyword-container').find('.keyword-row').each(function() {
    var number = $(this).find('td:last').find('input[name=bid-price[]]').val();

    var finalnumber = parseInt(number) + parseInt(finalnumber);

});​
2
  • I'm not sure if this is your issue, but you may want parseFloat if you are looking at decimal numbers. Commented May 30, 2012 at 13:41
  • What is exactly in the input fields? Did you try '.' and ',' as well as the decimal separator? Commented May 30, 2012 at 13:42

3 Answers 3

10

Change this:

var finalnumber = parseInt(number)+parseInt(finalnumber);  

To this:

finalnumber = finalnumber + parseFloat(number); 

Or:

finalnumber += parseFloat(number); 
  • parseInt can't hold decimal values. use parseFloat instead.
  • Don't declare finalnumber with var, becuase it hides the finalnumber in the outer scope.
Sign up to request clarification or add additional context in comments.

Comments

2

Just drop the var keyword inside your function in front of finalnumber. With that var you define a new variable under that name and scope. So basically you have two versions of finalnumber and just add to the local one (the one inside the function and not the global one).

On the other hand you should change parseInt to parseFloat as you are working with decimal numbers (See answer of @gdoron).

$('#chosen-keyword-container').find('.keyword-row').each(function() {
  var number = $(this).find('td:last').find('input[name=bid-price[]]').val();

  finalnumber = parseFloat(number) + finalnumber;  
});

On a sidenote: You can drop the parseInt() inside the function for finalnumber. This variable is always a number value and so there is no need to convert it.

Comments

1

change the addition line as follows

finalnumber = finalnumber + parseFloat(number);

Comments

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.