Addition operator not working in JavaScript

徘徊边缘 提交于 2019-12-02 15:08:57

问题


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 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));
}



回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!