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.
- parseInt()
- parseFloat()
- 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.
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 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:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article