Tuesday, 24 April 2012

Converting String value to integer in Javascript



function add()
{
var a=document.getElementById("text1").value
var b=document.getElementById("text2").value
var c = parseFloat(a) + parseFloat(b);
alert(c)
document.getElementById("text3").value=c
}


<input type='text' id='text1'  />
<input type='text' id='text2' />
<input type='text' id='text3' />

<input type='button'  value='add'  onclick='add()'>

created three textboxes
textbox1 has id text1
textbox2 has id text2
textbox3 has id text3

and add button to perform addition of values in textbox1 and textbox2 and displaying the result in textbox3
the value we input in textbox is in string
so we add integer number we get som different value
to convert string values to integer
we need to use parse command

example we provided value 2 and 3 to textbox 1 and textbox 2
these vlaues are in string we need to convert those values to integer
use parse

such as

parseFloat(a)
parseFloat(b)

another way

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


3 comments: