Javascript: parseFloat not working -
i using jquery pull data web page, comes array following values (.5, .25, 1.25, 3.75) trying add. here's code snippet:
var th = 0; (thisrow in objgrid) { var hours = objgrid[thisrow]['hours']; th = th+parsefloat(hours); console.log(hours); $("#msgbox").html("showing records week: " + thisdate + ". total hours week : " + th); }
in console.log getting hours - 0, 0 , 1, 3 , totaling 4. if don't use parsefloat still same results, (thought nan). doing wrong?
i think must have other problem, describing should work. example (here's bad-but-direct translation of code):
var grid = [ ".5", ".25", "1.25", "3.75" ]; var th = 0; (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 should change code anyhow:
don't use
for ( x in )
iterate on array; use numeric loop:for (var i=0,len=a.length;i<len;++i)
always
var
variables. you're using , overwriting globalthisrow
variable. when usefor ... in
,for (var x in o)
(unless have declared variable earlier in function).you should use
th += ...
instead ofth = th + ...
, because it's shorter , dryer.you should use
*1
instead ofparsefloat
. it's faster, less typing, , doesn't lie when have janky string.
Comments
Post a Comment