Coder Perfect

Instead of calculating the sum, adding two numbers concatenates them.

Problem

I’m adding two numbers, but I’m not getting the right answer.

For example, adding 1 and 2 yields 12 instead of 3.

I’m not sure what I’m doing wrong in this code.

Asked by okconfused

Solution #1

, rather than numerals. Prefixing a text with + is the simplest way to generate a number from it:

var x = +y + +z;

Answered by elclanrs

Solution #2

Number() is all I use:

var i=2;  
var j=3;  
var k = Number(i) + Number(j); // 5  

Answered by gerard

Solution #3

To convert the strings back to numbers, utilize the parseInt() method in javaScript. Because they’re strings right now, adding two strings concatenates them, giving you “12.”

Answered by mitim

Solution #4

If the text begins with “0,” the radix is octal/8, and so on. Use parseInt(…), but make sure you supply a radix value; otherwise, you’ll run into multiple issues (if the string begins with “0,” the radix is octal/8, and so on).

var x = parseInt(stringValueX, 10);
var y = parseInt(stringValueY, 10);

alert(x + y);

Hope this helps!

Answered by Zorayr

Solution #5

In general, the following information may be helpful.

Because the data from the form is treated as a string, the + will concatenate rather than add, causing your difficulty.

You should always pass supposedly numeric data from a form through parseInt() or parseFloat(), depending on whether you want an integer or a decimal, when reading it from a form.

It’s important to note that neither function turns a string to a number. Instead, it will parse the string from left to right until it reaches an invalid numeric character or the end, at which point it will convert what was approved. That contains one decimal point in the case of parseFloat, but not two.

After the valid number, everything else is just ignored. If the string does not begin with a number, they both fail. The result will be NaN.

A good general purpose technique for numbers from forms is something like this:

var data=parseInt(form.elements['data'].value); //  or parseFloat

You can use: if you’re willing to merge an invalid string to 0.

var data=parseInt(form.elements['data'].value) || 0;

Answered by Manngo

Post is based on https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum