Dear Friends,
Today we are going to discuss about the following topics.
1. What is meant by parseInt, when it will be used?
2. What is meant by parseFloat, when in will be used?
Whenever we are capturing any number value in HTML forms, by default it will be number. So to do any mathematical it needs to be converted. With can convert any string in to number with parseInt(), which is an inbuilt JavaScript method.
But, this parseInt() Method will be used if we are dealing with integer values only. Since it won’t recognize the Floating values like 10.73, 11.77, 3.44…
In such cases we use parseFloat() Method.
Let me explain this with an Example as follows.
Lest us create simple HTML form like follows.
In this Example we will be having 3 input fields. First two input fields will be firstNumber and lastNumber respectively.
Once user enter first number and second number and click on the add button, the result will be displayed in the 3rd input field.
Our HTML Code will look like as follows:
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <table> <tr> <td>First Number</td><td><input type="text" name="" id="firstNumber"></td> </tr> <tr> <td>Second Number</td><td><input type="text" name="" id="secondNumber"></td> </tr> <tr> <td>Result</td><td><input type="text" name="" id="result"></td> </tr> <tr> <td></td><td><input type="button" value="Add" onclick="add()"></td> </tr> </table> </body> </html>
It will give you output as follows.
Lest we create a java script function which captures the first number and second number and display its result in the result field after adding it.
Our JavaScript Code will look like as follows:
<script> function add() { var firstNumber = document.getElementById("firstNumber").value; //Checking whether user Entered any value in the Input field or not if (firstNumber == "") { alert("First Number is required") return; } //Converting string in to Float value firstNumber = parseFloat(firstNumber); if (isNaN(firstNumber)) { alert("Please Enter a Valid firstNumber") return; } var secondNumber = document.getElementById("secondNumber").value; if (secondNumber == "") { alert("Second Number is required") return; } secondNumber = parseFloat(secondNumber); if (isNaN(secondNumber)) { alert("Please Enter a Valid secondNumber") return; } document.getElementById("result").value = firstNumber + secondNumber; } </script>
Please visit the following Blog posts for the
JavaScript Examples with Detailed Explanations.
I have come across so many difficult situations
while learning JavaScript. I thought I can share my experience in my blog http://blog.sunlineitsolutions.com/ to the people which may be helpful for
them.
I hope I might help you! Thank you!