Adding two numbers results in a string


Problem

trying to do something like

var x = $('#myVar1').val();
var y = $('#myVar2').val();
var z = x + y;

results in "12" and not "3".



Solution

because both variables are strings and not numbers. the easiest way would be

var x = $('#myVar1').val();
var y = $('#myVar2').val();
var z = +x + +y;

The Unary + operator converts its operand to Number type. The Unary - operator converts its operand to Number type, and then negates it. But you have to know wether the value is positive or negative.

Another way is

var x = $('#myVar1').val();
var y = $('#myVar2').val();
var z = Number(x) + Number(x);

Or - depending on the values you're working with - this:

var x = $('#myVar1').val();
var y = $('#myVar2').val();
var z = parseFloat(x) + parseFloat(x);

Comments




Please sign-in to post a comment