214

I am adding two numbers, but I don't get a correct value.

For example, doing 1 + 2 returns 12 and not 3

What am I doing wrong in this code?

function myFunction() {
  var y = document.getElementById("txt1").value;
  var z = document.getElementById("txt2").value;
  var x = y + z;
  document.getElementById("demo").innerHTML = x;
}
<p>
  Click the button to calculate x.
  <button onclick="myFunction()">Try it</button>
</p>
<p>
  Enter first number:
  <input type="text" id="txt1" name="text1" value="1">
  Enter second number:
  <input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>
Ivar
  • 4,655
  • 12
  • 45
  • 50
okconfused
  • 3,109
  • 3
  • 21
  • 36
  • What type of values are you expecting as input? Integers or decimals? – Zorayr Jan 24 '13 at 08:20
  • 1
    A text input value will be string and strings will always concatenate instead of addition – hank Jan 24 '13 at 08:27
  • 1
    A good write-up on converting is [in this Answer](http://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript#answer-1133814). – akTed Jan 24 '13 at 08:29
  • 1
    Possible duplicate of [How to add two strings as if they were numbers?](https://stackoverflow.com/questions/8976627/how-to-add-two-strings-as-if-they-were-numbers) – Organic Advocate Jul 11 '17 at 18:59
  • 1
    If you have an ``, you can simply get its `.valueAsNumber` property directly. – Sebastian Simon Aug 30 '18 at 16:30
  • Using parseInt() you can convert string to int. – Rabby Sep 29 '20 at 03:56

24 Answers24

383

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;
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
elclanrs
  • 85,039
  • 19
  • 126
  • 159
  • 4
    out of curiousity (myself not a JavaScript programmer) (and I think this would improve the answer), what does the `+`-prefix do with strings? – Sebastian Mach Jan 24 '13 at 08:10
  • 30
    The above code is a bit bizarre and will confuse less seasoned developers. The code will also fail JSLint for confusing use of '+'. – Zorayr Jan 24 '13 at 08:23
  • 2
    @phresnel: [unary + operators](http://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators) – akTed Jan 24 '13 at 08:28
  • 11
    @AKTed: Actually I wanted to provoke elclanrs to describe it a bit _within_ his answer. Of course I am not unable to do the google search myself; but it would (imo) improve the quality of the answer, especially because using prefix-+ for string conversion is pretty uncommon in other programming languages and might confuse newbies. (however, thanks for sharing the link) – Sebastian Mach Jan 24 '13 at 08:37
  • True. But, if you have in your minds-eye a better-quality Answer but don't want to just post your own because it's just duplicating with some expansion, you could improve the Answer yourself. :) Answerer(s) might not deliver, for any number of reasons. – akTed Jan 24 '13 at 08:45
  • i have tried to do this var x = +y + +z; but geeting NaN share problem – Sajith Jan 30 '14 at 10:21
  • @Zorayr so much for anyone using something as jslint to analyze code that is dynamic... great way to restrict yourself – mmm Apr 22 '14 at 21:41
  • elclanrs I have an array defined. I am trying to update it using the key e.g. `arr[i].qty += qn;` the `qn` is a number, so is the `qty` but, it looks like they are behaving as strings/texts. Then I tried to wrap them with `Number()`, `ParseInt()`, yet both of them fails to achieve what I need. How can I update the array value? The funny thing is... when subtracting, this works `arr[i].qty -= 1;` , to say the the digit itself. Passed through a variable, it fails. – aspiring May 22 '15 at 06:07
  • Perfect, it worked with just `+` as you said. `arr[i].qty += +qn;` – aspiring May 22 '15 at 06:08
  • perfectly worked in a for loop in angular 2 . thank you – Amir Ghezelbash Feb 21 '17 at 07:22
  • 2
    I would discourage anyone from using this shortcut. I know that actually parsing a string into a number requires more code but at least the code clearly matches the intention. – Si Kelly May 10 '17 at 12:33
  • @kmario23 how are you today? this answer about summation numbers not strings!!! This is clear when you try cast string to number you got NAN, please check this fork of your fiddle with variables contains numeric values: http://jsfiddle.net/QMaster/zt7zq5cn/1/ – QMaster Nov 26 '17 at 00:16
  • @Zorayr luckily it doesn't get caught it lint – pcbabu Nov 10 '18 at 03:01
  • Save my day man!!! – Mike Victoria Apr 13 '21 at 09:01
146

I just use Number():

var i=2;  
var j=3;  
var k = Number(i) + Number(j); // 5  
Scott
  • 20,335
  • 7
  • 59
  • 71
gerard
  • 1,703
  • 1
  • 11
  • 14
30

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".

L84
  • 42,350
  • 55
  • 167
  • 243
mitim
  • 3,107
  • 5
  • 19
  • 24
  • 1
    I'm not sure `parseInt()` is the best option here given that the OP's function is adding two user-entered "numbers", not two "integers". – nnnnnn Jan 24 '13 at 08:17
  • 2
    @nnnnnn I think, that could easily be amended with [`parseFloat`](https://developer.mozilla.org/docs/JavaScript/Reference/Global_Objects/parseFloat) should the OP provide more input. – Yoshi Jan 24 '13 at 08:25
  • 1
    @Yoshi - Yes, yes it could, but given that the answer doesn't actually say anywhere that `parseInt()` only returns integers, and doesn't explain any of `parseInt()`'s "quirks" - which could be a problem with user-entered data - I thought it was worth mentioning. (I didn't actually downvote or anything.) – nnnnnn Jan 24 '13 at 08:42
  • Yes, I had made an assumption that the input would be integers since they gave an example of 1 + 2, but you're right - parseFloat() may be better if they are just any 'numbers'. – mitim Jan 24 '13 at 09:23
22

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!

Zorayr
  • 20,232
  • 5
  • 111
  • 102
  • 6
    I'm not sure `parseInt()` is the best option here given that the OP's function is adding two user-entered "numbers", not two "integers". – nnnnnn Jan 24 '13 at 08:16
  • 1
    Unless he is expecting floating point values, I think using this approach still works great. – Zorayr Jan 24 '13 at 08:24
  • 2
    This is no longer a problem in ES6. The radix may be safely omitted. `parseInt("012")` works fine, returning 12. Of course, you still have to careful with things like `[1,2].map(parseInt)`. –  Sep 23 '16 at 19:07
10

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 like 3+'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 get NaN, 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;
Manngo
  • 8,349
  • 6
  • 50
  • 74
7

Just add a simple type casting method as the input is taken in text. Use the following:

    var y = parseInt(document.getElementById("txt1").value);
    var z = parseInt(document.getElementById("txt2").value);
    var x = y + z;
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
6

This won't sum up the number; instead it will concatenate it:

var x = y + z;

You need to do:

var x = (y)+(z);

You must use parseInt in order to specify the operation on numbers. Example:

var x = parseInt(y) + parseInt(z); [final soulution, as everything us]
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Pushp Singh
  • 537
  • 7
  • 10
5

Simple

var result = parseInt("1") + parseInt("2");
console.log(result ); // Outputs 3
Murtaza Khursheed Hussain
  • 14,714
  • 7
  • 52
  • 78
3

This code sums both the variables! Put it into your function

var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = (y +z);
document.getElementById("demo").innerHTML = x;`
tiny sunlight
  • 6,096
  • 3
  • 18
  • 41
taha
  • 41
  • 3
2

Or you could simply initialize

var x = 0; ( you should use let x = 0;)

This way it will add not concatenate.

George Tiganila
  • 120
  • 2
  • 13
1

It's very simple:

<html>

    <body>
        <p>Click the button to calculate x.</p>
        <button onclick="myFunction()">Try it</button>
        <br/>
        <br/>Enter first number:
        <input type="text" id="txt1" name="text1">Enter second number:
        <input type="text" id="txt2" name="text2">
        <p id="demo"></p>

        <script>
            function myFunction() {
                var y = document.getElementById("txt1").value;
                var z = document.getElementById("txt2").value;
                var x = +y + +z;
                document.getElementById("demo").innerHTML = x;
            }
        </script>
    </body>
</html>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
1

Try this:

<!DOCTYPE html>
<html>

    <body>
        <p>Add Section</p>

        <label>First Number:</label>
        <input id="txt1"  type="text"/><br />
        <label>Second Number:</label>
        <input id="txt2"  type="text"/><br />

        <input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
        <p id="demo"></p>

        <script>
            function myFunction() {
                document.getElementById("demo").innerHTML = Date();
            }

            function addTwoNumber(){
                var a = document.getElementById("txt1").value;
                var b = document.getElementById("txt2").value;

                var x = Number(a) + Number(b);
                document.getElementById("demo").innerHTML = "Add Value: " + x;
            }
        </script>
    </body>
</html>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mohammed Ebrahim
  • 825
  • 1
  • 12
  • 22
1

You are missing the type conversion during the addition step...
var x = y + z; should be var x = parseInt(y) + parseInt(z);

 <!DOCTYPE html>

 <html>
 <body>
  <p>Click the button to calculate x.</p>
  <button onclick="myFunction()">Try it</button>
  <br/>
  <br/>Enter first number:
  <input type="text" id="txt1" name="text1">Enter second number:
  <input type="text" id="txt2" name="text2">
  <p id="demo"></p>
 <script>
    function myFunction() 
    {
      var y = document.getElementById("txt1").value;
      var z = document.getElementById("txt2").value;
      var x = parseInt(y) + parseInt(z);
      document.getElementById("demo").innerHTML = x;
    }
 </script>
 </body>
 </html>
AbcAeffchen
  • 12,535
  • 15
  • 46
  • 62
sharjeel
  • 41
  • 3
1
    <head>
        <script type="text/javascript">
            function addition()
            {
                var a = parseInt(form.input1.value);
                var b = parseInt(form.input2.value);
                var c = a+b
                document.write(c);
            }
        </script>
    </head>

    <body>
        <form name="form" method="GET">
        <input type="text" name="input1" value=20><br>
        <input type="text" name="input2" value=10><br>
        <input type="button" value="ADD" onclick="addition()">
        </form>
    </body>
</html>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Lakshmi
  • 11
  • 1
  • 3
    Welcome to SO! Can you please explain a little bit more? Your answer is only code, so it might work, but the questioner (or other visitors!) might not understand why it works. – Chilion Dec 11 '15 at 09:32
1

If we have two input fields then get the values from input fields, and then add them using JavaScript.

$('input[name="yourname"]').keyup(function(event) {
    /* Act on the event */
    var value1 = $(this).val();
    var value2 = $('input[name="secondName"]').val();
    var roundofa = +value2+ +value1;

    $('input[name="total"]').val(addition);
});
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Asad Ali
  • 594
  • 6
  • 10
1
  <input type="text" name="num1" id="num1" onkeyup="sum()">
  <input type="text" name="num2" id="num2" onkeyup="sum()">
  <input type="text" name="num2" id="result">

  <script>
     function sum()
     {

        var number1 = document.getElementById('num1').value;
        var number2 = document.getElementById('num2').value;

        if (number1 == '') {
           number1 = 0
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }
        else if(number2 == '')
        {
           number2 = 0;
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }
        else
        {
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }

     }
  </script>
Ahmad Ajaj
  • 11
  • 2
0

You can do a precheck with regular expression wheather they are numbers as like

function myFunction() {
    var y = document.getElementById("txt1").value;
    var z = document.getElementById("txt2").value;
    if((x.search(/[^0-9]/g) != -1)&&(y.search(/[^0-9]/g) != -1))
      var x = Number(y)+ Number(z);
    else
      alert("invalid values....");
    document.getElementById("demo").innerHTML = x;
  }
Ram
  • 657
  • 1
  • 12
  • 25
  • Instead of regular expressions you could just use parseXX and check for NaN return. – hank Jan 24 '13 at 08:30
  • Validating user-entered data is always a good plan, but you still need to convert the input strings to numeric form before you can do a numeric addition. – nnnnnn Jan 24 '13 at 08:36
0

Here goes your code by parsing the variables in the function.

<html>
  <body>
    <p>Click the button to calculate x.</p>
    <button onclick="myFunction()">Try it</button>
    <br/>
    <br/>Enter first number:
    <input type="text" id="txt1" name="text1">
    <br>Enter second number:
    <input type="text" id="txt2" name="text2">
    <p id="demo"></p>
    <script>
      function myFunction() {
        var y = parseInt(document.getElementById("txt1").value);
        var z = parseInt(document.getElementById("txt2").value);
        var x = y + z;
        document.getElementById("demo").innerHTML = x;
      }
    </script>
  </body>
</html>

Answer

Enter image description here

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Manoj Krishna
  • 187
  • 1
  • 3
  • 11
0

Use parseFloat it will convert string to number including decimal values.

 function myFunction() {
      var y = document.getElementById("txt1").value;
      var z = document.getElementById("txt2").value;
      var x = parseFloat(y) + parseFloat(z);
      document.getElementById("demo").innerHTML = x;
    }


<p>
  Click the button to calculate x.
  <button onclick="myFunction()">Try it</button>
</p>
<p>
  Enter first number:
  <input type="text" id="txt1" name="text1" value="1">
  Enter second number:
  <input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>
Poorna Rao
  • 317
  • 3
  • 20
0

You can also write : var z = x - -y ; And you get correct answer.

<body>

<input type="text" id="number1" name="">
<input type="text" id="number2" name="">
<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

    <script>
    function myFunction() {
        var x, y ;

        x = document.getElementById('number1').value;
        y = document.getElementById('number2').value;

        var z = x - -y ;

        document.getElementById('demo').innerHTML = z;
    }
    </script>
</body>
P.A.010
  • 23
  • 6
0

If Nothing works then only try this. This maybe isn't Right way of doing it but it worked for me when all the above failed.

 var1 - (- var2)
Jay Momaya
  • 1,056
  • 13
  • 24
0

This can also be achieved with a more native HTML solution by using the output element.

<form oninput="result.value=parseInt(a.valueAsNumber)+parseInt(b.valueAsNumber)">
  <input type="number" id="a" name="a" value="10" /> +
  <input type="number" id="b" name="b" value="50" /> =
  <output name="result" for="a b">60</output>
</form>

https://jsfiddle.net/gxu1rtqL/

The output element can serve as a container element for a calculation or output of a user's action. You can also change the HTML type from number to range and keep the same code and functionality with a different UI element, as shown below.

<form oninput="result.value=parseInt(a.valueAsNumber)+parseInt(b.valueAsNumber)">
  <input type="range" id="a" name="a" value="10" /> +
  <input type="number" id="b" name="b" value="50" /> =
  <output name="result" for="a b">60</output>
</form>

https://jsfiddle.net/gxu1rtqL/2/

Darren
  • 63,390
  • 21
  • 126
  • 134
-1

Perhaps you could use this function to add numbers:

function calculate(a, b) {
  return a + b
}
console.log(calculate(5, 6))
G. Trialonis
  • 55
  • 1
  • 10
-3

An alternative solution, just sharing :) :

var result=eval(num1)+eval(num2);
Hkachhia
  • 4,130
  • 5
  • 35
  • 71
user3201772
  • 79
  • 1
  • 2
  • 13
  • Not a nice as using the [jQuery arithmetic plugin](https://github.com/cbrandolino/jQuery-basic-arithmetic-plugin), but I like it. – Paul Draper Mar 26 '15 at 20:00
  • In principle, there’s nothing wrong with `eval()`, but _you should never use `eval` with user data_. – Manngo Sep 19 '20 at 01:17
  • @PaulDraper I think using a jQuery plugin for such a simple task is well and truly overkill, especially when JavaScript has a built-in solution. – Manngo Sep 19 '20 at 01:18