tags:

views:

57

answers:

2

Hello,

var a = 1;
var b = 2;
var c = a+b;

c will show as 12; but I need 3

How do I do it using JavaScript?

Thanks Jean

+4  A: 

It looks like you have strings and not numbers, you need parseInt() or prseFloat() (if they may be decimals) here, like this:

var a = "1";
var b = "2";
var c = parseInt(a, 10) + parseInt(b, 10);
//or: var c = parseFloat(a) + parseFloat(b);

You can test the difference here, it's worth noting these are not jQuery but base JavaScript functions, so this isn't dependent on the jQuery library in any way.

Nick Craver
yes thanks, worked out Got to wait 8 mins before I accept your answer.
Jean
+3  A: 

Try this -

var c = parseInt(a, 10) + parseInt(b, 10);
Sachin Shanbhag
You should always use a radix on `parseInt()`, otherwise numbers starting with a `0` will be treated as base 16 by default.
Nick Craver
@Nick - Thanks a lot for this information.
Sachin Shanbhag
Watch out with this one, it will use "0" as a magic prefix for octal, so: `parseInt("010") == 8`.
Douglas