0

Addition operator isn't working for me in Javascript. If I do 5+5, it gives me 55 instead of 10. How can I fix this?

var numberOne = prompt (Enter first number.);
if (numberOne > 0.00001) {
 var numberTwo = prompt(Enter the second number.);
if (numberTwo > 0.00001) {
var alertAnswer = alert (numberOne + numberTwo);
}
}
1
  • parseInt(), they are not numbers but strings Commented Jan 7, 2014 at 1:29

4 Answers 4

4

You're reading in strings, and concatenating them. You need to convert them to integers with parseInt.

IE:

var numberOne = parseInt(prompt("Enter first number."), 10);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I was just wondering what that number 10 does. Thanks.
0

There are two main changes that need to take place. First, the prompts must use Strings. Second, you must parse the user's String input to a number.

var numberOne = prompt ("Enter first number.");
if (numberOne > 0.00001) {
     var numberTwo = prompt("Enter the second number.");
if (numberTwo > 0.00001) {
    var alertAnswer = alert (parseInt(numberOne,10) + parseInt(numberTwo,10));
}

6 Comments

Too early to omit radix
@zerkms I assumed the op was using a decimal based number system.
how would JS know that if you don't specify that explicitly?
Isn't that the default?
@zerkms Your right. An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
|
0

you need to use parseInt

as in

 var a = parseInt(prompt("Please enter a number")); 

Comments

0

Just for completeness: a potential problem with parseInt() (in some situations) is that it accepts garbage at the end of a numeric string. That is, if I enter "123abc", parseInt() will happily return 123 as the result. Also, of course, it just handles integers — if you need floating-point numbers (numbers with fractional parts), you'll want parseFloat().

An alternative is to apply the unary + operator to a string:

 var numeric = + someString;

That will interpret the string as a floating-point number, and it will pay attention to trailing garbage and generate a NaN result if it's there. Another similar approach is to use the bitwise "or" operator | with 0:

var numeric = someString | 0;

That gives you an integer (32 bits). Finally, there's the Number constructor:

var numeric = Number( someString );

Also allows fractions, and dislikes garbage.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.