Thursday, 26 April 2012

How to convert string to number in javascript?

Definition: Convert String to Number.

The Number() function converts the object argument to a number that represents the object's value.
If the value cannot be converted to a legal number, NaN is returned.
In short,
Number() method will convert string to number.

Example A:
Javascript function
 
function add(a,b)
{
    var ans;
    var i = a;
    var j = b;
    ans = Number(a) + Number(b);
 
    alert("Your answer: " + ans);
}

 <div>
        <input type="text" id="txta" />
        <input type="text" id="txtb" />
        <input type="button" id="btnAdd" value="Addition" onclick="add(document.getElementByI('txta').value,document.getElementById('txtb').value);" />
          </div>
Output:



Example B:
<script type="text/javascript" language="javascript">

var test1= new Boolean(true);
var test2= new Boolean(false);
var test3= new Date();
var test4= new String("999");
var test5= new String("999 888");

document.write(Number(test1)+ "<br />");

document.write(Number(test2)+ "<br />");
document.write(Number(test3)+ "<br />");
document.write(Number(test4)+ "<br />");
document.write(Number(test5)+ "<br />");

</script> 

Output:
1
0
1335442904505
999
NaN

No comments:

Post a Comment