How To Convert String into Number

Date Published: 29/08/2020 Published By: JaiSchool

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>

Publish A Comment

Leave a Reply

Your email address will not be published. Required fields are marked *