JavaScript

How to convert strings to numbers using JavaScript?

How to convert strings to numbers using JavaScript?, someone asked me to explain?

In this article we will discuss how to convert strings to numbers using JavaScript. There are different methods available in JavaScript to convert.

Here forms allows user to enter two numbers and add them. We are discuss  using three  functions.

  1.          parseInt()
  2. parseFloat()
  3.       isNan

Without parsing add two numbers in JavaScript:

 

function addNumbers() {

        var firstNumber = document.getElementById("txtFirstNumber").value;

        var secondNumber = document.getElementById("txtSecondNumber").value;

        document.getElementById("txtResult").value = firstNumber + secondNumber;

    }

 

If we add two numbers using above JavaScript for example if we enter 52 and 88 it will result 5288. JavaScript concatenates the numbers instead of adding them. This is because the value property of the textbox is returning the number in a string format.

Without parsing add two numbers in JavaScript

Parse by integer in JavaScript:

 

if we enter 45 and 54 it will result 99

 

    function addNumbers() {

        var firstNumber = parseInt(document.getElementById("txtFirstNumber").value);

        var secondNumber = parseInt(document.getElementById("txtSecondNumber").value);

        document.getElementById("txtResult").value = firstNumber + secondNumber;

    }

 Parse by integer in JavaScript:

Parse by float in JavaScript

 

Create an html page and Copy and paste the following code on it.

 

<script type="text/javascript">

    function addNumbers() {

        var firstNumber = parseFloat(document.getElementById("txtFirstNumber").value);

        if (isNaN(firstNumber)) {

            alert("Please enter a valid number in the first numbertextbox");

            return;

        }

        var secondNumber = parseFloat(document.getElementById("txtSecondNumber").value);

        if (isNaN(secondNumber)) {

            alert("Please enter a valid number in the second numbertextbox");

            return;

        }

        document.getElementById("txtResult").value= firstNumber + secondNumber;

    }

 

 

    </script>

<h2>Addition using javascript</h2>

 

<table style="border:1px solid black;">

    <tr>

        <td>First Number</td>

        <td>

            <input type="text" id="txtFirstNumber" />

        </td>

    </tr>

    <tr>

        <td>Second Number</td>

        <td>

            <input type="text" id="txtSecondNumber" />

        </td>

    </tr>

    <tr>

        <td>

        </td>

        <td>

            <input type="button" value="Add" id="btnAdd" onclick="addNumbers()"/>

        </td>

    </tr>

    <tr>

        <td>Result</td>

        <td>

            <input type="text" id="txtResult" />

        </td>

    </tr>

   

</table>

 

 

Output:

Parse by float in JavaScript

Post your comments / questions