ShotNet ShotNet - 2 months ago 7x
HTML Question

Addition returns wrong value in JavaScript

When I tried with additions of variables I saw that:

I think it's because this doesn't contain an integer.

var month = $("#monthd").val();
var J = 1;
var D = 8;
var K = J + D;
var U = J + month;

As you can see in fiddle J + month returns 110 instead of 11, why?


its a string, so the number you are adding gets coerced into a string as well. "10" + "1" = "101";

simply wrap the value returned in a Number Construct

var month = Number($("#monthd").val());

additionally you can use parseInt if the values are integers.

var month = parseInt($("#monthd").val(), 10);

the , 10 is important to parse it with base 10.