Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two numbers?

Tags:

javascript

I wrote a JavaScript calculator... but suppose when I give my first number as 2 and the second number as 3, the result is showing 23, but I wanted to add the two numbers.

Can anyone please help me? It is also happening when I try to minus the two numbers. Why isn't this working?

var cal = prompt("Please enter what type of calculation you want to do\n
if you wanna add enter = 1\n
if you want to minus enter = 2\n
if you want to divide enter = 3\n
if you want to multiply enter = 4");

if (cal == 1) {
    var a = prompt("Please enter your first number");
    var b = prompt("please enter your second number");

    alert("The result is , " + a+b);
}

if (cal == 2) {
    var c = prompt("Please enter your first number");
    var d = prompt("please enter your second number");

    alert("the result is , " + c - d);
}
like image 745
Pramito Rahman Avatar asked Apr 30 '13 05:04

Pramito Rahman


2 Answers

Try this:

var cal = prompt("Please enter what type of calculation you want to do\n" +
  "if you want to add enter = 1\n" +
  "if you want to minus enter = 2\n" +
  "if you want to divide enter = 3\n" +
  "if you want to multiply enter = 4");

if (cal == 1) {
    var a = prompt("Please enter your first number");
    var b = prompt("please enter your second number");

    alert("The result is , " + (Number(a) + Number(b)));
}

else if (cal == 2) {
    var c = prompt("Please enter your first number");
    var d = prompt("please enter your second number");

    alert("the result is , " + (Number(c) - Number(d)));
}
like image 82
Satpal Avatar answered Sep 28 '22 01:09

Satpal


The + sign is used to concatenate strings together, not to add them together mathematically.

You need to wrap your variables in parseInt(), e.g.

alert("The result is , " + parseInt(a)+parseInt(b));
like image 31
Danny Beckett Avatar answered Sep 28 '22 00:09

Danny Beckett