问题
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:
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);
回答2:
There are two main changes that need to take place. First, the prompts must use String
s. 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));
}
回答3:
you need to use parseInt
as in
var a = parseInt(prompt("Please enter a number"));
回答4:
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.
来源:https://stackoverflow.com/questions/20962410/addition-operator-not-working-in-javascript