JavaScript: When 2+2 = 22!

In our previous blog post we looked at how to retrieve values from various HTML form controls.

For instance the following JavaScript code shows you how to retrieve the value typed in a textbox.

See the Pen DwahE by 101 Computing (@101Computing) on CodePen.

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.

See the Pen FCGDH by 101 Computing (@101Computing) on CodePen.

This JavaScript code retrieves the values from the textboxes and add them together… But when you try to add 2 and 2 together the outcome is not 4 but 22!!!

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:

To convert text into a real/float we can use the parseFloat() function as follows:

So the code for our basic online calculator should be as follows:

See the Pen vpHKs by 101 Computing (@101Computing) on CodePen.

Share Button
Posted in Computer Science, JavaScript

Our Latest Book

Follow this blog