0

So I have a string called hoursString that looks like

4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|

I split the string into an array and what I am trying to do is add up all the numbers and return it to the html page in the div "test".

JAVASCRIPT:

var hours=hoursString.split("|");

    var total=0;
    for (var i=0;i<hours.length;i++)
        {
        total += hours[i];
        }
    document.getElementById("test").innerHTML=total;

The result is NaN. Can someone tell me what I am doing wrong? Thanks!

kchow23
  • 111
  • 2
  • 2
  • 11

4 Answers4

2
4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|

remove the last |, split will otherwise add an empty string at the end of the array which will give NaN and NaN + number evaluates to NaN

edit: and yes, parseFloat is necessary too, otherwise the result will be a string instead of NaN

Christian
  • 3,551
  • 1
  • 28
  • 24
1
var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|",
    hours = hoursString.split("|"),
    total = 0;
for (var i = 0; i < hours.length; i++) {
    total += parseFloat(hours[i]) || 0; // see explanation
}
document.getElementById("test").innerHTML = total;

Why the || 0? Because it checks if the string is "", if so the || operand will return the second value, in this case 0.

This will output 25.740000000000002. See this answer on the cause of the "wrong" result, and here is a working fiddle.

Community
  • 1
  • 1
Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
0

Your issue is that each element in hours is still a string value even though it is written as a number. The easiest way to fix this would be to use javascripts parseFloat() function.

Example:

var hours=hoursString.split("|");

    var total=0;
    for (var i=0;i<hours.length;i++)
        {
        total += parseFloat(hours[i]);
        }
    document.getElementById("test").innerHTML=total;

EDIT: Changed from parseInt to parseFloat

Dylan N
  • 527
  • 3
  • 13
0
var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|"
var hours=hoursString.split("|");

var total=0;
var idx = 0;
for(idx in hours) {
    total += +hours[idx];
}

alert(total);

FIDDLE

ar3
  • 3,883
  • 3
  • 21
  • 22