Reputation: 3224
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);
});
Upvotes: 3
Views: 16569
Reputation: 150253
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.finalnumber
with var
, becuase it hides the finalnumber
in the outer scope.Upvotes: 10
Reputation: 3045
change the addition line as follows
finalnumber = finalnumber + parseFloat(number);
Upvotes: 1
Reputation: 74046
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.
Upvotes: 2