0

It is showing 60 + 5 as 605 instead of 65

g = document.getElementById("height1").value * 12;
alert(g);    <---- This is showing 60
h = document.getElementById("height2").value;
alert(h);   <---- This is showing 5
b = g+h;
alert(b);    <---- This is showing 605

Any ideas

Dommy Domo
  • 11
  • 1

4 Answers4

3

Use parseInt() to convert to integer. + in Javascript is both for adding and concatenation.

EvilZebra
  • 1,072
  • 8
  • 18
3

Javacript is not a strongly typed language. It does it's best to interpret the type of variables and generally, if you try to add a string-like variable to an integer-like variable, it will interpret it as string concatenation.

You could force the variables to be interpreted as integers like this:

 b = parseInt(g) + parseInt(h);

Or, using other tricks that will force the variable to become numeric, like this:

 b = (g*1) + (h*1);
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • Make sure to [always include the radix](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters) when calling `parseInt()` – Dave Nov 07 '14 at 21:55
0

how about b = (g+h)?

make sure the vars are integers, else convert them to integers

Medda86
  • 1,582
  • 1
  • 12
  • 19
0

If the values of those HTML elements are strings (like in text input boxes?) then what you're doing is concatenating strings, not adding numbers.

You need to 1) be sure the input values are actually numeric, and 2) convert the string to an integer using parseInt().

mc01
  • 3,750
  • 19
  • 24