How To Convert String into Number

When we receive the input field’s value in Javascript. Its data type is ‘string’ even if the value of type attribute number <input type="number">.

So its type can be easily changed from string to number by using Javascript predefined Number() method.

EXAMPLE: Use of Number Method

<html>
<body>

<input type="number" id="first-n" />
<input type="number" id="second-n" />
<button onclick="calculate()">Calculate</button>

<script>
function calculate()
{
  var first=Number(document.getElementById("first-n").value);
  var second=Number(document.getElementById("second-n").value);
  alert(first+second);
}
</script>
</body>
</html>

Leave a Comment