Its actually easy to do basic math in Visual Basic 5.0/6.0 and Visual Basic.NET 2002/2003 and Visual Basic 2005. Both the VB 5.0/6.0 and .NET Framework has a Math Class/Module to perform more advanced calculations. Unfortunately I do not know much beyond the scope of basic Math calculations, so don’t expect anything beyond the basics.
Update: Since many are apparently wanting to make a calculator based application I added a new link to a Tutorial for VB .NET on making a basic calculator. The link is with the other VB calculator example links near the bottom of this post.
Operators for Basic Math
- + = Addition
- – = Subtraction
- * = Multiply
- / = Division *ForwardSlash is More Exact, Includes Decimal Remainders
- \ = Division *BackSlash Returns Integers only with No Decimals/Remainders
To perform basic math is easy with any version of VB. You can perform Math on variables and/or actual numbers…
Note: In Visual Basic 5.0 and Visual Basic 6.0 you should change the .NET Codes in this article from Integer types to Longs.
Dim myMath As Integer myMath = 2 + 2 MsgBox(myMath)
The Messagebox will return the number ‘4’ since it added ‘2 + 2?. Adding actual variables it just as easy…
Dim myMath As Integer Dim myMath2 As Integer myMath = 2 myMath2 = 5 MsgBox(myMath * myMath2)
The first message with the forward slash includes the remainder or decimal portion and the back slash will return the integer number ‘2’ with no decimal. So, the first messagebox returns = ‘2.4’ and the Second message box returns = ‘2’…
Subtraction was just as easy. Just use the Dash – operator as the example does above. The message box above returns = ‘7’ since ’12 – 5 = 7?.
You can also perform calculations on String variable types. You use them similar to the number based types. I would recommend using the Val() function in Visual Basic. Val will return or convert the Integers in a String to Doubles that is better to do when you are working with numbers as values to be calculated. Even if the String contains a non-number value along with a number value, Val() will try to convert the characters to a number value. Example…
Dim myMath As String Dim myMath2 As String myMath = "12k" myMath2 = "5j" MsgBox(Val(myMath) * Val(myMath2))
The messagebox above will return a ’60’ since Val() only cared about the Interger characters and not any non-number based values.
If your interested, I have both a VB 6.0 and VB.NET 2005/2008 Example of how to make a basic calculator application. Click Here for the Classic VB Example and Click Here for the VB.NET 2005/2008 Example.
Update: Click this link if you want to view a tutorial on specifically making a basic calculator via Visual Basic .NET.
As you can see, performing basic math is very easy to do. There are other Functions in Visual Basic as well like Sqr (Sqrt in .NET), Sin, Cos, and more. But that is beyond the scope of this article. Maybe at another time. Anyways, Have Fun!