Jump to content

Javascript adding numbers

LessThanSatisfactory
var num1 = prompt("What is number 1?");var num2 = prompt("What is number 2?");var num3 = num1 + num2;{    alert("The answer is " + num3);}

A bit of my code goes a little like this, but instead of mathematically adding the two numbers, it shows (number1)(number2), for example, if I try to add 1 and 2, I get 12.

Build: Fx-8120@4.1ghz,  Gtx770@1.0ghz,  16gb Patriot memory,  Cheap case from thermaltake

Link to comment
Share on other sites

Link to post
Share on other sites

This is because you are concatenating strings. You need to cast your inputs to numbers first and then add them:

var num1 = Number(prompt("What is number 1?"));var num2 = Number(prompt("What is number 2?"));var num3 = num1 + num2;alert("The answer is " + num3);

Made you a fiddle: http://jsfiddle.net/3qvPt/

 

There's also parse functions such as parseInt & parseFloat.

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×