views:

189

answers:

3

Hi I have a string of numbers separated by commas, "100,200,300,400,500" that I'm splitting into an array using the javascript split function:

var data = [];
data = dataString.split(",");

I'm trying to parse the values of the array using parseFloat and then store them back into the array. I'd then like to add up the numbers in the array and store it as another variable, "dataSum".

I've got the following code, but I can't get it working:

var dataSum = "";

for (var i=0; i < data.length; i++) {
    parseFloat(data[i]);
    dataSum += data[i];
}

So at the end of all this, I should be able to access any of the parsed numbers individually data[0], data[1], etc... and have a total number for dataSum. What am I doing wrong?

+2  A: 

You are using parseFloat but not assigning the result to anything.

From wcschools:

The parseFloat() function parses a string and returns a floating point number.

Additionally, adding a number to a string will concatenate the results, so you should default your dataSum to 0, not to "".

var dataSum = 0.0;

for (var i=0; i < data.length; i++) {
    dataSum += parseFloat(data[i]);
}
Oded
+5  A: 

(1)

var dataSum = "";

You are initializing dataSum as a string. For strings, the += is a concatenation operator, so you'll get 100200300400500 because of concatenation. You should initialize it to 0:

var dataSum = 0;

(2)

parseFloat does not modify the input parameter. The float value is returned. So you should use

dataSum += parseFloat(data[i]);

(3)

var data = [];
data = dataString.split(",");

The 2nd assignment will override the 1st. Just write

var data = dataString.split(",");

(BTW, ECMAScript 5 supports this one-liner:

return "100,200,300,400,500".split(/,/).map(parseFloat).reduce(function(x,y){return x+y;})

)

KennyTM
Does the one line "dataSum += parseFloat(data[i]);" parseFloat the individual data values? So for instance, if I called data[3] separately at a later time, I would want that to have been formatted properly using parseFloat. Or do I have to add another line to the loop?
George
+1 for the ECMAScript 5 example, I'm loving how some people are starting to put them into their answers now :-)
Andy E
@George: If you want `data[3]` as a float later, you need to use `parseFloat(data[3])` (or simpler `+data[3]`, almost same effect).
KennyTM
I see, is there anyway to set all the values in the array as a float at once so that I don't have to use parseFloat() every time I call a value?
George
@George: Jhonny's answer explained it. Basically, `data[i] = parseFloat(data[i]);`.
KennyTM
ohh, duh. thanks a lot!
George
+5  A: 

parseFloat returns a value, which you should use to make your calculation, also, you should initialize your dataSum variable to a numeric value.

var dataSum = 0;

for (var i=0; i < data.length; i++) {
    var current = parseFloat(data[i]);
    dataSum += current;
    // to save back onto array
    // data[i] = current;
}
Jhonny D. Cano -Leftware-