In our previous blog post we looked at how to retrieve values from various HTML form controls.
So let’s apply this to a tiny “online calculator” project to perform a sum (+ operator) of two numbers. We would need:
- two textboxes for the user to enter the two numbers to be added.
- one textbox to display the result of adding the two numbers.
This is because textbox entries are providing values as text (String Data Type) and not number.
If we want to perform mathematical operations we need to convert this text into numbers.
There are two main types of numbers: Integer and Real.
- Integers are whole numbers with no decimal points such as 3 or -7 or 101.
- Reals (aka float) are numbers which can have decimals such as 3.1415 or -4.99.
To convert text into an integer we can use the parseInt() function as follows:
var st="2" var myNumber=parseInt(st);
To convert text into a real/float we can use the parseFloat() function as follows:
var st="3.14" var myNumber=parseFloat(st);
So the code for our basic online calculator should be as follows: