Javascript concatenating numbers, not adding up

前端 未结 3 1724
梦如初夏
梦如初夏 2020-12-07 04:14

It keeps concatenating my numbers into 2111 instead of 5. Why is this? I\'ve tried using parseInt with no luck. res3 btw represents a query into my database that I\'m execut

相关标签:
3条回答
  • 2020-12-07 04:32

    If the values are strings then they will be concatenated, not added numerically.

    Try constructing a number from the string value:

    dt_total_hours += Number(res3.fieldByName(dt_cost_per_hour));
    //                ^------ Force a number here instead of a string.
    
    0 讨论(0)
  • 2020-12-07 04:32

    Yeah, it's reading them as strings. I find that a dirty, awful hack to get them interpreted as numbers is to take x += y and change it to x += y / 1.0 (or / 1 for integer). Usually does the trick.

    0 讨论(0)
  • 2020-12-07 04:37

    you can parse your data according to desired type as follow

    dt_total_hours += parseInt(res3.fieldByName(dt_cost_per_hour));
    

    you can also use parseFloat method as well

    0 讨论(0)
提交回复
热议问题