1. Basic Calculator Tutorial
In this tutorial, Basic Calculator in VB.Net, we will look at creating a basic calculator. The
calculator will have the following functionality:
Addition
Subtraction
Division
Multiplication
Square Root
Exponents (Power Of)
Clear Entry
Clear All
There will be a 2nd tutorial that will cover some more advanced features such as
Adding a number to memory
Removing a number from memory
Calculating with a number in memory
Entering numbers by typing
The first thing you need to do is create a new project in Visual Studio (or Visual Basic Express
Edition if thats what you use). Once you have created your new project you need to create your
user interface, your user interface should look like this:
2. Your user interface will consist of
Buttons 0 through 9
Buttons for
o Addition
o Subtraction
o Division
o Multiplication
o Exponents (x^)
o Inverse (1/x)
o Square Root (sqrt)
Decimal
Equals
Backspace
CE (Clear Entry)
C (Clear All)
ReadOnlyTextBox for input (Make sure TabStop is also set to False)
How you setup your user interface is up to you, but remember people are used to a calculator
looking a certain way so you may wish to follow my example.
In this tutorial I will show you how to code two of the number buttons (since all 10 are the same
except the zero button), how to code the calculations buttons, the clear buttons and the backspace
buttons. Before writing any code you need to add the following variables to the top (Globals):
01 'variables to hold operands
02 PrivatevalHolder1 AsDouble
03 PrivatevalHolder2 AsDouble
04 'Varible to hold temporary values
05 PrivatetmpValue AsDouble
06 'True if "." is use else false
07 PrivatehasDecimal AsBoolean
08 PrivateinputStatus AsBoolean
09 PrivateclearText AsBoolean
'variable to hold
10
Operater
3. 11 PrivatecalcFunc AsString
These variables will be used through out our program thats why they're globals. Now, before any
calculations can be done, the user needs to be able to enter numbers into the input box, so lets
take a look at how to do that (Ill use the number 1 key and the zero key).
Number one key:
PrivateSubcmd1_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) Handlescmd1.Click
02 'Check the inputStatus
03 IfinputStatus Then'Its True
04 'Append values to the value
05 'in the input box
06 txtInput.Text += cmd1.Text
07 Else 'Value is False
08 'Set the value to the value of the button
09 txtInput.Text = cmd1.Text
10 'Toggle inputStatus to True
11 inputStatus = True
12 EndIf
13 EndSub
When a user clicks a number button (in this case the number one button) we check the status of
the inputStatus flag. If its true then we know we can just append the next value to the end of
whats currently in the input box, otherwise we just enter the number into the input box. All the
remaining numbers follow this procedure, except the zero button, this one is slightly different as
we don't want the user to be able to enter zero as the first number (this is covered more in the
decimal button functionality).
So lets take a look at how we code the zero button:
PrivateSubcmd0_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) Handlescmd0.Click
02 'Check the input status
03 IfinputStatus Then'If true
04 'Now check to make sure our
05 'input box has a value
06 IftxtInput.Text.Length>= 1 Then
07 'Add our zero
08 txtInput.Text += cmd0.Text
09 EndIf
10 EndIf
4. 11 EndSub
First we check the status of the inputStatus flag, if its true we know we can enter a number in
the box. Here we do a second check, we make sure the length of the text in the input box is at
least 1 (it has a value), if so we enter the zero into the input box.
For adding a decimal to our input box we need to first make sure our input box doesn't already
contain one, then we need to make sure our input box has a value (don't want the user to be able
to enter a decimal as the first value). Then we make sure the value in the input area isn't 0 (zero),
this we will handle later.
If all those are true then we enter the decimal then toggle the hasDecimal to True, so the user
cant enter a 2nd one. Now, if the input area doesn't have a value, we enter 0., as we assume the
user is wanting to work with a decimal value such as 0.5. Lets take a look at the procedure for
doing this:
PrivateSubcmdDecimal_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) HandlescmdDecimal.Click
02 'Check for input status (we want true)
03 IfinputStatus Then
04 'Check if it already has a decimal (if it does then do nothing)
05 IfNothasDecimal Then
06 'Check to make sure the length is > than 1
07 'Dont want user to add decimal as first character
08 IftxtInput.Text.Length> 1 Then
09 'Make sure 0 isnt the first number
10 IfNottxtInput.Text = "0"Then
11 'It met all our requirements so add the zero
12 txtInput.Text += cmdDecimal.Text
'Toggle the flag to true (only 1 decimal per
13
calculation)
14 hasDecimal = True
15 EndIf
16 Else
17 'Since the length isnt> 1
18 'make the text 0.
19 txtInput.Text = "0."
20 EndIf
21 EndIf
22 EndIf
23 EndSub
As you can see, we check all the items mentioned above, if they're True we add the decimal,
5. otherwise we add 0. to the input area.
Next we want to be able to add numbers together. The first thing we do here is to make sure the
input box has a value (Length > 1). If it does then we check the calcFunc value. The
calcFunction variable will be used to tell our CalculateTotals procedure which calculation to
perform. Here, if the value is empty (String.Empty) we assign the value of our input box to a
variable, valHolder1, which will hold the first part of all calculations, then clear out the input
box so the user can enter a 2nd number.
If the calcFunc variable isnt empty then we call our CalculateTotals procedure to display a total
to the user. We then assign the value of Add to our variable for the next turn through, then we
toggle the bb]hasDecimal[/b] flag to False.
Now lets take a look at how we accomplished this:
PrivateSubcmdAdd_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) HandlescmdAdd.Click
02 'Make sure out input box has a value
03 IftxtInput.Text.Length<> 0 Then
04 'Check the value of our function flag
05 IfcalcFunc = String.Empty Then'Flag is empty
06 'Assign the value in our input
07 'box to our holder
08 valHolder1 = CType(txtInput.Text, Double)
09 'Empty the input box
10 txtInput.Text = String.Empty
11 Else'Flag isnt empty
12 'Call our calculate totals method
13 CalculateTotals()
14 EndIf
15 'Assign a value to our calc function flag
16 calcFunc = "Add"
17 'Toggle the decimal flag
18 hasDecimal = False
19 EndIf
20 EndSub
Believe it or not, all the other basic calculation buttons are the same as the Add button, with the
exception of what we set calcFunc to. In the other buttons we set this variable to the calculation
we want to perform, Subtract,
Divide, Multiply, and so on, so there really isn't a reason to show how that is done since we did
the Add button and the others are the same.
Lets say you want to give the user the option to calculation Exponents, 4^2 for example. To code
6. this button you need a couple of checks before doing anything. First we need to check and make
sure the input area has a value, if it does then we check to see the value of the calcFunc variable.
If this is empty, we then convert the value of the input area to a Double and assign it to the
valHolder1 variable to hold on to, this will be used for the calculations in the CalculateTotals
procedure and empth the value from the input area.. If its not empty we directly call the
CalculateTotals function as this means the user has already entered 2 numbers.
We then assign the value of PowerOf to our calcFunc variable, this will tell CalculateTotals
what calculation to perform, and toggle the hasDecimal flag to False.
Lets take a look at how we accomplished all of this:
PrivateSubcmdPowerOf_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) HandlescmdPowerOf.Click
02 'Make sure the input box has a value
03 IftxtInput.Text.Length<> 0 Then
04 'Check if the calcFunc flag is empty
05 IfcalcFunc = String.Empty Then
06 'Assign the value of the input box to our variable
07 valHolder1 = CType(txtInput.Text, Double)
08 'Empty the input box
09 'So the user can enter the power of value
10 txtInput.Text = String.Empty
11 Else
12 'Call the calculate totals method
13 CalculateTotals()
14 EndIf
15 'Assign our flag the value of "PowerOf"
16 calcFunc = "PowerOf"
17 'Reset the decimal flag
18 hasDecimal = False
19 EndIf
20 EndSub
Doing a Square Root is somewhat different as it doesn't take 2 values, just the number you want
the square root of, so some of the checking required in the other calculations isn't required here.
For a Square Root we first check to ensure the input area has a value. If it does have a value we
assign the value of the input area, converted to a Double, to our tmpValue variable.
Once we have the value, we call the System.Math.Sqrt Method to perform the calculations on the
tmpValue variable. Once this is complete we assign the resulting value to our input area, then
toggle the hasDecimal flag to False.
7. Lets take a look at how this is done:
PrivateSubcmdSqrRoot_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) HandlescmdSqrRoot.Click
02 'Make sure the input box has a value
03 IftxtInput.Text.Length<> 0 Then
04 'Assign our variable the value in the input box
05 tmpValue = CType(txtInput.Text, Double)
06 'Perform the square root
07 tmpValue = System.Math.Sqrt(tmpValue)
08 'Display the results in the input box
09 txtInput.Text = CType(tmpValue, String)
10 'Clear the decimal flag
11 hasDecimal = False
12 EndIf
13 EndSub
The Equals button is quite simple. Here, we first check to make sure our input area has a value
and that our valHolder1 variable isn't a zero (Divide by 0 is a bad thing). If both of these are true
we call the CalculateTotals procedure to perform our calculations based on the value of the
calcFunc flag. We then clear the value of calcFunc and toggle the hasDecimal flag to False.
This is done like this:
PrivateSubcmdEqual_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) HandlescmdEqual.Click
02 'Make sure theres a value in the input box
03 'And that our temp value isnt 0
04 IftxtInput.Text.Length<> 0 AndAlsovalHolder1 <> 0 Then
05 'Call the calculate totals method
06 CalculateTotals()
07 'Clear the calcFunction value
08 calcFunc = String.Empty
09 'Toggle the decimal flag
10 hasDecimal = False
11 EndIf
12 EndSub
We have 3 more buttons to look at before we look at the CalculateTotals procedure. First we'll
look at the backspace button.For the backspace, first we need to make sure the input are has a
value. If it does then we retrieve the next to last character and see if its a decimal, if it is we
toggle the hasDecimal flag to False. Next we create an Integer variable (loc) to hold the length
8. of the contents in the input area. From there we use Remove, along with loc to remove the last
character of the string for each time the user clicks the backspace button.
PrivateSubcmdBackspace_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) HandlescmdBackspace.Click
02 'Declare locals needed
03 Dimstr AsString
04 Dimloc AsInteger
05 'Make sure the text length is > 1
06 IftxtInput.Text.Length> 0 Then
07 'Get the next to last character
08 str = txtInput.Text.Chars(txtInput.Text.Length - 1)
09 'Check if its a decimal
10 Ifstr = "."Then
11 'If it is toggle the hasDecimal flag
12 hasDecimal = False
13 EndIf
14 'Get the length of the string
15 loc = txtInput.Text.Length
16 'Remove the last character, incrementing by 1
17 txtInput.Text = txtInput.Text.Remove(loc - 1, 1)
18 EndIf
19 EndSub
The last 2 buttons I'm going to demonstrate are the CE (Clear entry) and C (Clear all) buttons.
These are very simple. First the clear entry button. What we do here is set the value in the input
area to empty (String.Empty), and the hasDecimal flag to false.
PrivateSubcmdClearEntry_Click(ByValsender AsSystem.Object, ByVale
1
AsSystem.EventArgs) HandlescmdClearEntry.Click
2 'Empty the input box
3 txtInput.Text = String.Empty
4 'Toggle the decimal flag
5 hasDecimal = False
6 EndSub
The clear all button required a bit more code as we do more with this button. Here we set our 2
holder variables, valHolder1 and valHolder2 to 0 (zero), we then set the calcFunc flag to
String.Empty and the hasDecimal flag to False, like this:
PrivateSubcmdClearAll_Click(ByValsender AsSystem.Object, ByVale
01
AsSystem.EventArgs) HandlescmdClearAll.Click
02 'Empty the text in the input box
9. 03 txtInput.Text = String.Empty
04 'Clear out both temp values
05 valHolder1 = 0
06 valHolder2 = 0
07 'Set the calc switch to empty
08 calcFunc = String.Empty
09 'Toggle the hasDecimal flag
10 hasDecimal = False
11 EndSub
Those are the buttons you need for a Basic calculator. The final thing we're going to look at is
the procedure that actually does the calculations, CalculateTotals. Here the first thing we do is
set our variable valHolder2 to the current value of the input area. We then do a Select Case on
the value of calcFunc so we know which calculations to perform. We perform our calculations
(add, subtract, divide, multiply, exponent, etc) and set the results to the input area so the user can
see their results. Finally we set the inputEntry flag to False. THisiw hat this procedure looks
like:
01 PrivateSubCalculateTotals()
02 valHolder2 = CType(txtInput.Text, Double)
03 SelectCasecalcFunc
04 Case"Add"
05 valHolder1 = valHolder1 + valHolder2
06 Case"Subtract"
07 valHolder1 = valHolder1 - valHolder2
08 Case"Divide"
09 valHolder1 = valHolder1 / valHolder2
10 Case"Multiply"
11 valHolder1 = valHolder1 * valHolder2
12 Case"PowerOf"
13 valHolder1 = System.Math.Pow(valHolder1, valHolder2)
14 EndSelect
15 txtInput.Text = CType(valHolder1, String)
16 inputStatus = False
17 EndSub
NOTE: For the Exponents (Power Of) we use the System.Math.Pow Method for calculating the
value.
Thats it, thats how you create a basic calculator in VB.Net. I hope you find this tutorial helpful. I
am including the project file with this tutorial, but remember this solution is under the GNU
10. GENERAL PUBLIC LICENSE so you may not remove the header from the files or turn this
project in as your homework assignment.
I know I am forced to go with the honor system in this, but if you do just turn this in as your
assignment not only will you be cheating, but you will learn nothing, and subsequently wont
know enough to become a programmer once you get out of school.
I will be doing a 2nd part to this tutorial where I look at adding more advanced functionality to
this calculator, such
as adding a number to memory, removing a number from memory, calculations with a number in
memory and more. Also, I will be creating a C# version of this calculator for the C# users.
Thank you for reading!