Javascript Sum Values
Solution 1:
Make sure the values are numbers, otherwise they will concat instead of suming.
a = parseInt(a, 10); // a is now int
Solution 2:
Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you're not saying:
var a = '2'; // or something similar
Or if the values are parsed from somewhere, be sure to call parseInt(a, 10)
on them before doing the addition, 10 being the radix.
Or as pointed out in the comments the Number
function would probably suit your purposes.
Solution 3:
The author has probably put "simplified" code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using "Number()" solved the problem:
var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value);
Solution 4:
This works fine:
var a = 2;
var b = 5;
var c = a + b; // c is now 7
Solution 5:
The code you show will not work the way you describe. It will result in 7
.
However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.
This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt()
[docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter (radix
) to ensure the casting from string to number uses the base you expect. (The lack of info on radix
in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt()
.)
Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN()
[docs].
Post a Comment for "Javascript Sum Values"