Forum Moderators: open

Message Too Old, No Replies

How to convert string to integer in JavaScript

parseInt, parseFloat, Number Function or unary operator

         

sawkat

2:37 am on Feb 12, 2009 (gmt 0)

10+ Year Member



function tipp(){
var a= document.getElementById("textbox1").value;
var b= document.getElementById("textbox2").value;
var c= a+b;
myform.total.value = c;
}
now if i put in the textbox1 and textbox1 , like --
a= 5 and b = 3
that shold be c = 8
but comming 58
so now i need a+b = 8 , how can i do ?

rocknbil

3:10 am on Feb 12, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try: var c = parseInt(a+b);

sawkat

4:11 am on Feb 12, 2009 (gmt 0)

10+ Year Member



no - not working

Lang

5:17 am on Feb 12, 2009 (gmt 0)

10+ Year Member



Try var c = parseFloat(a) + parseFloat(b);

sawkat

5:52 am on Feb 12, 2009 (gmt 0)

10+ Year Member



yesssss thanks Lang
thanks for help

coopster

5:21 pm on Feb 12, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, sawkat.

JavaScript is recognizing the types of variables here as string and rather than use a mathematical addition calculation, JavaScript is using string concatenation to combine the two strings.

JavaScript has a few built-in functions for handling conversion of strings to numbers including

parseInt
and
parseFloat
for integers and floats. There is also a
Number()
function. You might also consider the unary plus operator. Fast and easy:
function tipp() 
{
var a = +document.getElementById("textbox1").value;
var b = +document.getElementById("textbox2").value;
var c = a + b;
myform.total.value = c;
}

Fotiman

6:23 pm on Feb 12, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Personally, I like the parseInt method, simply because it's more obvious what is happening.


function tipp() {
var a = parseInt(document.getElementById("textbox1").value);
var b = parseInt(document.getElementById("textbox2").value);
var c = a + b;
myform.total.value = c;
}