0

This is returning 2 strings when i am trying to a 2 intergers. this is probably a really easy question! thanks

<script>
function add() {
var noO = prompt("please enter a number:");
var noT = prompt("please enter a second number:");
var no1 = noO;
var no2 = noT;
var res = no1 + no2;
alert("the adiition of thoes 2 numbers is: " + res);
}
</script>
  • 1
    prompt returns a string ... try `Number(prompt("..."))` – Jaromanda X May 29 '17 at 09:22
  • 1
    I think you need to parse `no1` and `no2` so JS recognises them as integers: `parseInt(no1) + parseInt(no2);` – Sandman May 29 '17 at 09:24
  • 1
    try [`parseFloat(prompt())`](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwic1taF5ZTUAhUIro8KHVxSDJcQFggnMAA&url=https%3A%2F%2Fwww.w3schools.com%2Fjsref%2Fjsref_parsefloat.asp&usg=AFQjCNHnX2N78WPvEGHs8qefO1xV4Wm98A&sig2=iBmjlPnhrnZFy1MYWupYKQ) – prasanth May 29 '17 at 09:29

2 Answers2

0

You need to use parseInt on no1 and no2 like follows:

  var noO = prompt("please enter a number:");
  var noT = prompt("please enter a second number:");
  var no1 = noO;
  var no2 = noT;
  var res = parseInt(no1, 10) + parseInt(no2, 10);
  alert("the adiition of thoes 2 numbers is: " + res);

EDIT

In addition, it is probably worth noting that parseInt should always be used with a radix specified based on the required behaviour:

An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10

E.g. a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal.. There are many examples on the web page link above.

Sandman
  • 2,247
  • 1
  • 13
  • 26
0
function add() {
  var noO = parseInt(prompt("please enter a number:"));
  var noT = parseInt(prompt("please enter a second number:"));
  var no1 = noO;
  var no2 = noT;
  var res = no1 + no2;
  alert("the adiition of thoes 2 numbers is: " + res);
}
Kalaiselvan
  • 2,095
  • 1
  • 18
  • 31
  • 1
    Please add a short explanation to your post, what your code does and why it solves the initial problem. Don't just post a block of uncommented code. – user1438038 May 29 '17 at 10:31
  • Sure!.. prompt alway's will return a String i just convert that String into Integer. so it solves the initial problem – Kalaiselvan May 29 '17 at 10:36