Javascript concatenates numbers without adding

He keeps putting my numbers together at 2111 instead of 5. Why is that? I've tried using parseInt with no luck. res3 btw represents a request to my database that I am executing.

var dt_total_hours = 0;

            dt_total_hours += res3.fieldByName(dt_cost_per_hour);
            dt_total_hours += res3.fieldByName(dt_prod_dt_hours);
            dt_total_hours += res3.fieldByName(dt_prod_rate);
            dt_total_hours += res3.fieldByName(dt_cost_per_unit);
            dt_total_hours += res3.fieldByName(dt_scrap_startup_cost);
            dt_total_hours += res3.fieldByName(dt_labor_expense);
            dt_total_hours += res3.fieldByName(dt_since_issues_first_noticed);
            dt_total_hours += res3.fieldByName(dt_wo_for_maint);
            dt_total_hours += res3.fieldByName(dt_investigation);
            dt_total_hours += res3.fieldByName(dt_maint_made_bandaid);
            dt_total_hours += res3.fieldByName(dt_parts_outsourcing);
            dt_total_hours += res3.fieldByName(dt_get_equip_out_prod);
            dt_total_hours += res3.fieldByName(dt_perm_repair);
            dt_total_hours += res3.fieldByName(dt_equip_back_to_prod);
            dt_total_hours += res3.fieldByName(dt_to_full_prod_speed);
            dt_total_hours += res3.fieldByName(dt_other);

      

+3


source to share


3 answers


If the values ​​are strings, they will be concatenated rather than added numerically.

Try to plot a number from a string value :



dt_total_hours += Number(res3.fieldByName(dt_cost_per_hour));
//                ^------ Force a number here instead of a string.

      

+8


source


Yes, it reads them as strings. I find the dirty, horrible hack to get them interpreted as numbers is to take x += y

and change it to x += y / 1.0

(or / 1

for an integer). Usually does the trick.



+1


source


you can parse the data according to the type you want as follows: dt_total_hours + = parseInt (res3.fieldByName (dt_cost_per_hour));

You can also use parseFloat method

0


source







All Articles