Javascript: parseFloat not working

PruitIgoe picture PruitIgoe · Feb 9, 2011 · Viewed 11.5k times · Source

I am using jQuery to pull some data from a web page, it comes back as an array with the following values (.5, .25, 1.25, 3.75) which I am trying to add. Here's my code snippet:

var th = 0;
    for (thisrow in objGrid) {
        var hours = objGrid[thisrow]['hours'];
        th = th+parseFloat(hours);
        console.log(hours);

        $("#msgbox").html("Showing records for week: " + thisDate + ". Total Hours for the week : " + th);
   }

in console.log I am getting this for the hours - 0, 0 , 1, 3 and it is totaling 4. If I don't use parseFloat I still get the same results, (thought I would get NaN). What am I doing wrong?

Answer

Phrogz picture Phrogz · Feb 9, 2011

I think you must have some other problem, as what you are describing should work. For example (here's a bad-but-direct translation of your code):

var grid = [ ".5", ".25", "1.25", "3.75" ];
var th = 0;
for (x in grid){
  var h = grid[x];
  var hrs = parseFloat(h);
  th = th + hrs;
  console.log( h, hrs );
}
//   .5 0.5
//  .25 0.25
// 1.25 1.25
// 3.75 3.75

console.log( th );
// 5.75

A few things you should change about your code anyhow:

  1. Don't use for ( x in a ) to iterate over an array; use a numeric for loop: for (var i=0,len=a.length;i<len;++i)

  2. Always var your variables. You're using and overwriting a global thisrow variable. Even when you use for ... in, do it like so for (var x in o) (unless you have declared your variable earlier in the function).

  3. You should use th += ... instead of th = th + ..., just because it's shorter and DRYer.

  4. You should use *1 instead of parseFloat. It's faster, less typing, and doesn't lie to you when you have a janky string.