Javascript (+) Sign Concatenates Instead of Giving Sum of Variables

Javascript: "+" sign concatenates instead of giving sum of variables

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

javascript (+) sign concatenates instead of giving sum?

Here value gives you a string, hence the concatenation. Try parsing it as an Number instead:

var sum = parseInt(numberOne) + parseInt(numberTwo);

See the demo fiddle.

Javascript (+) sign concatenates instead of giving sum of variables

Use this instead:

var divID = "question-" + (i+1)

It's a fairly common problem and doesn't just happen in JavaScript. The idea is that + can represent both concatenation and addition.

Since the + operator will be handled left-to-right the decisions in your code look like this:

  • "question-" + i: since "question-" is a string, we'll do concatenation, resulting in "question-1"
  • "question-1" + 1: since "queston-1" is a string, we'll do concatenation, resulting in "question-11".

With "question-" + (i+1) it's different:

  • since the (i+1) is in parenthesis, its value must be calculated before the first + can be applied:

    • i is numeric, 1 is numeric, so we'll do addition, resulting in 2
  • "question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".

Adding two numbers concatenates them instead of calculating the sum

They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with +:

var x = +y + +z;

Number concatenates instead of being added

try to use below way

 if(ship == ''){        ship = 0;        ship = parseFloat(ship);    }
b = parseFloat(ship) + parseFloat(b);

How does adding String with Integer work in JavaScript?

"" + 1          === "1"
"1" + 10 === "110"
"110" + 2 === "1102"
"1102" - 5 === 1097
1097 + "8" === "10978"

In JavaScript, the + operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.

When you use the - operator, however, the string is converted back into a number so that numeric subtraction may occur.

When you then "add" a string "8", string concatenation occurs again. The number 1097 is converted into the string "1097", and then joined with "8".



Related Topics



Leave a reply



Submit