Adding two numbers concatenates them instead of calculating the sum
Solution 1:
They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with +
:
var x = +y + +z;
Solution 2:
I just use Number()
:
var i=2;
var j=3;
var k = Number(i) + Number(j); // 5
Solution 3:
You need to use javaScript's parseInt()
method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".
Solution 4:
Use parseInt(...) but make sure you specify a radix value; otherwise you will run into several bugs (if the string begins with "0", the radix is octal/8 etc.).
var x = parseInt(stringValueX, 10);
var y = parseInt(stringValueY, 10);
alert(x + y);
Hope this helps!
Solution 5:
The following may be useful in general terms.
-
First, HTML form fields are limited to text. That applies especially to text boxes, even if you have taken pains to ensure that the value looks like a number.
-
Second, JavaScript, for better or worse, has overloaded the
+
operator with two meanings: it adds numbers, and it concatenates strings. It has a preference for concatenation, so even an expression like3+'4'
will be treated as concatenation. -
Third, JavaScript will attempt to change types dynamically if it can, and if it needs to. For example
'2'*'3'
will change both types to numbers, since you can’t multiply strings. If one of them is incompatible, you will getNaN
, Not a Number.
Your problem occurs because the data coming from the form is regarded as a string, and the +
will therefore concatenate rather than add.
When reading supposedly numeric data from a form, you should always push it through parseInt()
or parseFloat()
, depending on whether you want an integer or a decimal.
Note that neither function truly converts a string to a number. Instead, it will parse the string from left to right until it gets to an invalid numeric character or to the end and convert what has been accepted. In the case of parseFloat
, that includes one decimal point, but not two.
Anything after the valid number is simply ignored. They both fail if the string doesn’t even start off as a number. Then you will get NaN
.
A good general purpose technique for numbers from forms is something like this:
var data=parseInt(form.elements['data'].value); // or parseFloat
If you’re prepared to coalesce an invalid string to 0, you can use:
var data=parseInt(form.elements['data'].value) || 0;