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
- ModuleNotFounEerror:No module named celery in Django Project
- How to get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
Related Article