Tropilac
Tropilac

Reputation: 43

I am trying to create a calculator with javascript.

I can get the input from a user and i can put it all into a sum, but it retuns NaN.

my code:

var input1 = prompt("input 1","0");
var operation = prompt("operation","+");
var input2 = prompt("input 2","0");
var ans = (input1 + intput2);

if (operation = "+")
{
    document.write("input1 + intput 2 = " + ans);
}
else
{ 
    document.write("Other operations coming soon!");
}

Upvotes: 0

Views: 50

Answers (2)

prasanth
prasanth

Reputation: 22510

Prompt return the string so you need to convert the string to number using parseFloat() .And check the spell of input2 in var ans .

var input1 = prompt("input 1", "10");
var operation = prompt("operation", "+");
var input2 = prompt("input 2", "2");
var ans = parseFloat(input1) + parseFloat(input2);

if (operation = "+") {
  document.write("input1 + intput 2 = " + ans);
} else {
  document.write("Other operations coming soon!");
}

Upvotes: 0

brk
brk

Reputation: 50346

There are couple of issues in this snippet.

  1. You need to convert input1 & input2 if mathematical addition is expected. + sign before these variables are unary operator
  2. There is a typo at intput2. In should me input2.
  3. In the if condition validate using == or ===. operation = "+" is just assigning the value

var input1 = prompt("input 1", "0");
var operation = prompt("operation", "+");
var input2 = prompt("input 2", "0");
var ans = (+input1 + +input2);

if (operation == "+") {
  document.write("input1 + intput 2 = " + ans);
} else {
  document.write("Other operations coming soon!");
}

Upvotes: 1

Related Questions