Reputation: 229
Given: I have elements with values of integers floats (thank you, Pointy) up to two decimal places (such as: 1.50 and 2.25).
Goal: Collect the values of several elements and add them together. (such as: 1.50 + 2.25 = 3.75 )
Code:
$(".quantity").keyup(function(){
var sum = 0.00;
var subTotals = document.getElementsByClassName("sub-total")
$.each(subTotals, function(){
sum += $(this).val() << 0
});
$("#products_revenue_income").val(sum)
});
Issue: I'm used to Ruby, so I presumed that iterating over an array of [1.5, 2.25] you could add the elements together with +=
, to get 3.75
, but my return value was 01.502.25
, appearing to (1) add a zero to the left and (2) treat the values as a string. When I added the shift operator <<
, it removed the left zero and treated the values like integers again, but it rounded the total, so my return value is 3
.
What I've tried: I've tried using parseFloat($(this).val()).toFixed(2)
within the block to make sure each value is treated as an integer but it doesn't appear to have any effect on the result.
Tech: jQuery version: 1.7.1.
Thank you for your time Let me know if you require any additional context.
Upvotes: 3
Views: 2454
Reputation: 4472
The jQuery method .val() will return a string-like object, so to convert it to a float to make your maths work OK you can use parseFloat:
sum += parseFloat($(this).val())
MDN docs for parseFloat:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
Example:
subTotals = [1.1, 2.2]
sum = 0
$.each(subTotals, function(idx, num){
sum += parseFloat(num)
})
console.log(sum) // Will print 3.3
Demo:
http://jsfiddle.net/sifriday/7q4qe4L3/
Upvotes: 3
Reputation: 5543
The problem is that val()
returns a string. Instead of shift, convert the values. The cleanest and simplest way to do this is by subtracting zero from the value.
$(".quantity").keyup(function(){
var sum = 0.00;
var subTotals = document.getElementsByClassName("sub-total")
$.each(subTotals, function(){
sum += $(this).val()-0
});
$("#products_revenue_income").val(sum)
});
This of course assumes that the values will always be numeric.
Upvotes: 1
Reputation: 128801
This is happening because jQuery's val()
method returns the value
property of the matched element which is a string type. This means you're falling into the string concatenation trap ("1"
+ "1"
= "11"
). You can convert your value into a number using a Unary plus (+
):
sum += +$(this).val();
Also worth noting that value
is a native property of this
, so you can drop the jQuery wrapper and method here altogether:
sum += +this.value;
Upvotes: 3