最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: "+" sign concatenates instead of giving sum of variables - Stack Overflow

programmeradmin2浏览0评论

I am currently creating a site that will help me quickly answer physics questions. As it happens, the code didn't run as expected, here is the code

if (option == "dv") {
    var Vinitial = prompt("What is the Velocity Initial?")
    var acceleration = prompt("what is the acceleration?")
    var time = prompt("what is the time?")

    Vfinal = Vinitial + acceleration * time

    displayV.innerHTML = "v= vf= " + Vfinal + "ms" + sup1.sup();
}

Now, let's say Vinitial was 9, acceleration was 2, and time was 3. When the code runs, instead of getting 15 for "Vfinal", I get 96. I figured out that it multiplies acceleration and time fine, and then just concatenates the 9 at the beginning, with 6 (the product of 2 * 3).

I have fixed it for now by using

Vfinal =  acceleration * time - (-Vinitial)

which avoids using the "+" sign, but I don't want to have to keep doing this. How do I fix it?

I am currently creating a site that will help me quickly answer physics questions. As it happens, the code didn't run as expected, here is the code

if (option == "dv") {
    var Vinitial = prompt("What is the Velocity Initial?")
    var acceleration = prompt("what is the acceleration?")
    var time = prompt("what is the time?")

    Vfinal = Vinitial + acceleration * time

    displayV.innerHTML = "v= vf= " + Vfinal + "ms" + sup1.sup();
}

Now, let's say Vinitial was 9, acceleration was 2, and time was 3. When the code runs, instead of getting 15 for "Vfinal", I get 96. I figured out that it multiplies acceleration and time fine, and then just concatenates the 9 at the beginning, with 6 (the product of 2 * 3).

I have fixed it for now by using

Vfinal =  acceleration * time - (-Vinitial)

which avoids using the "+" sign, but I don't want to have to keep doing this. How do I fix it?

Share Improve this question edited May 6, 2016 at 9:23 Keane Carotenuto asked May 6, 2016 at 9:21 Keane CarotenutoKeane Carotenuto 391 silver badge5 bronze badges 4
  • Convert the value from strings to int – Oisin Commented May 6, 2016 at 9:22
  • Vfinal = + Vinitial + acceleration * time - extra + at the start to enforce numerical operations. – Niet the Dark Absol Commented May 6, 2016 at 9:25
  • Each of your values Vinitial, acceleration and time are strings not numbers. As such this is defined behaviour. Try parsing the strings... e.g. Number.parseInt(Vinitial) – phuzi Commented May 6, 2016 at 9:26
  • 1 Possible duplicate of Javascript (+) sign concatenates instead of giving sum of variables – Yury Tarabanko Commented May 6, 2016 at 9:27
Add a ment  | 

4 Answers 4

Reset to default 5

you are dealing with strings here, and math operations on strings will mess up. Remember when ever you are doing math operations you have to convert the data into actual numbers and then perform the math.

Use parseInt() more Details here

Your code should change to

Vfinal = parseInt(Vinitial,10) + parseInt(acceleration,10) * parseInt(time,10);

Edit 1: If the numbers are decimal values then use parseFloat() instead

So the code would be

Vfinal = parseFloat(Vinitial) + parseFloat(acceleration) * parseFloat(time);

Object-Oriented JavaScript - Second Edition: As you already know, when you use the plus sign with two numbers, this is the arithmetic addition operation. However, if you use the plus sign with strings, this is a string concatenation operation, and it returns the two strings glued together:

var s1 = "web";
var s2 = "site";
s1 + s2; // website

The dual purpose of the + operator is a source of errors. Therefore, if you intend to concatenate strings, it's always best to make sure that all of the operands are strings. The same applies for addition; if you intend to add numbers, make sure the operands are numbers.

You can use "+" operator with prompt() to convert returned values from string to int

var Vinitial = +prompt("What is the Velocity Initial?");
var acceleration = +prompt("what is the acceleration?");
var time = +prompt("what is the time?");

Explanation:

var a = prompt('Enter a digit'); 
typeof a; // "string"
typeof +a; // "number"

If you will enter non-digit data +a gives you NaN. typeof NaN is "number" too :)

You will get the same result with parseInt():

var Vinitial = parseInt(prompt("What is the Velocity Initial?"), 10);
var acceleration = parseInt(prompt("what is the acceleration?"), 10);
var time = parseInt(prompt("what is the time?"), 10);

developer.mozilla: parseInt(string, radix);

  • string: The value to parse.

  • radix: 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 monly 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.

Epilogue:

Object-Oriented JavaScript - Second Edition: The safest thing to do is to always specify the radix. If you omit the radix, your code will probably still work in 99 percent of cases (because most often you parse decimals), but every once in a while it might cause you a bit of hair loss while debugging some edge cases. For example, imagine you have a form field that accepts calendar days or months and the user types 06 or 08.

Epilogue II:

ECMAScript 5 removes the octal literal values and avoids the confusion with parseInt() and unspecified radix.

The Problem is, Your value has been took it in a form of string .. so convert your value into Int using parseInt(accelaration).. then it will work ..

Vfinal = parseInt(Vinitial) + parseInt(acceleration) * parseInt(time)
//use ParseInt
var a=10,b=10;
var sum=parseInt(a+b);

ex:

parseInt(Vinitial + acceleration) * time
发布评论

评论列表(0)

  1. 暂无评论