Sum of an array of integers (strings?) Without losing decimal places

Considering : I have elements with integers floats (thanks Pointy) up to two decimal places (ex: 1.50 and 2.25).

Purpose . Collect the values โ€‹โ€‹of multiple elements and add them together. (for example: 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)
});

      

Problem . I'm used to Ruby, so I assumed that iterating over the array from [1.5, 2.25] could add elements along with +=

to get 3.75

, but my return value was 01.502.25

, appearing in (1), adding a zero to the left, and (2) processing values โ€‹โ€‹in as a string. When I added the shift operator <<

, it removed the left zero and treated the values โ€‹โ€‹as integers again, but rounded up the total, so my return value 3

.

What I have tried . I tried using parseFloat($(this).val()).toFixed(2)

in a block to make sure each value is treated as an integer, but it doesn't seem to affect the result.

Technology : jQuery version: 1.7.1.

Thank you for your time. Let me know if you need additional context.

+3


source to share


3 answers


This is because the jQuery method val()

returns a property of the value

matched element, which is a string type. This means that you are falling into the trap of string concatenation ( "1"

+ "1"

= "11"

). You can convert your value to a number using the unary plus ( +

):

sum += +$(this).val();

      



It's also worth noting which value

is a native property this

, so you can remove the wrapper and jQuery method altogether:

sum += +this.value;

      

+3


source


The jQuery.val () method will return a string-like object, so to convert it to float so that your math works fine, 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/

+2


source


The problem is what is val()

returning a string. Convert the values โ€‹โ€‹instead of changing. The cleanest and easiest way to do this is to subtract 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 assumes, of course, that the values โ€‹โ€‹will always be numeric.

+1


source







All Articles