Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numerical value of number input by user in a text field

I need to add up two numbers input by the user. To do that, I create two input fields, retrieve values from them , using .val(), in two separate variables and then add them. The problem is that the strings are added and not the numbers. For eg. 2 + 3 becomes 23 and not 5. please suggest what to do, except using type = number in the input boxes.

like image 989
Akash Avatar asked Feb 14 '12 16:02

Akash


2 Answers

You can use parseInt(...)

Example:

var num = parseInt("2", 10) + parseInt("3", 10);
// num == 5
like image 179
John Fisher Avatar answered Nov 09 '22 04:11

John Fisher


Use parseInt to convert a string into a number:

var a = '2';
var b = '3';
var sum = parseInt(a,10) + parseInt(b,10);
console.log(sum); /* 5 */

Keep in mind that parseInt(str, rad) will only work if str actually contains a number of base rad, so if you want to allow other bases you'll need to check them manually. Also note that you'll need to use parseFloat if you want more than integers.

like image 31
Zeta Avatar answered Nov 09 '22 04:11

Zeta