1

When calculating values within an Array I am getting this: total = "0212.16967.04". The correct total in this example is:1179.20

function calculateSum(){
  //build array of numbers
  amtArray = [];
  $('.amount').each(function (index, value) {		
    amtArray.push($(this).text()||0);
  });
  //calculate all values and return results 	
  var sum = sumArray(amtArray);
  console.log('sum ->', sum)
}
 
function sumArray(input) {
  var total = 0;
  for (idx=0; idx <= input.length-1; idx++) {
    total += input[idx];
  }
  return total;
}

calculateSum()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="amount">212.16</div>
<div class="amount">967.04</div>

Should output: 1179.20

3
  • 4
    Try "212.16" + "967.04" on the developer console - it's string concatenation. Convert to number before using the + operator. Commented Jun 13, 2017 at 14:58
  • 2
    Possible duplicate of Javascript (+) sign concatenates instead of giving sum of variables Commented Jun 13, 2017 at 14:59
  • use parseFloat() $('.amount').each(function (index, value) { amtArray.push(parseFloat($(this).text())||0); }); Commented Jun 13, 2017 at 15:00

5 Answers 5

4

You need to cast the value from string to number with an unary plus + (or by using Number or parseFloat, or any other operator which expects a number), otherwise if any of the operands is a string, all parts are treated as string and concatinated.

total += +input[idx];
//       ^
Sign up to request clarification or add additional context in comments.

Comments

2

The error here is you are concatenating strings, here's a solution:

var array = ["212.16", "967.04"]

function sumArray(input) {
  var total = 0;
  for (idx = 0; idx <= input.length - 1; idx++) {
    total += parseFloat(input[idx]);
  }
  return total;
}

console.log(sumArray(array));

Comments

1

In the function sumArray you can directly return the result of Array.prototype.reduce() using Number to work with numerical values:

const sumArray = arr =>  arr.reduce((a, b) => a + Number(b), 0);

console.log(sumArray(["212.16", "967.04"]));

Comments

0

You are concatenating string values rather than adding flowing pointing numbers. You can use parseFloat() to convert from string to float like this this:

function sumArray(input) {  //input = (2) ["212.16", "967.04"]
    var total = 0;
    for (idx=0; idx <= input.length-1; idx++) {
        total += parseFloat(input[idx]);    
    }
    return total;  
}

Comments

0

Aside from using a unary, parsefloat, Number you should also use toPrecision to get that last zero you indicated in your question

var val = document.getElementsByClassName('amount');

function calculateSum() {
  var total = 0;
  for (var i = 0; i < val.length; i++) {
    var value = val[i].textContent;
    total += +value;
  }
  return total.toPrecision(6);
}
val[1].insertAdjacentHTML('afterend', calculateSum());
<div class="amount">212.16</div>
<div class="amount">967.04</div>

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.