Welcome to Math Class
September 19th, 2007
The .NET math class provides you with several handy math routines you can use even if you’re not doing complex trigonometric or logarithmic functions. In this article we will take an introductory look at the non-trig, non-log, functions and how to use them in your code.
Abs
This is an old familiar command to VB Classic and BASIC programmers. It returns the absolute value of a number and it accepts SByte, Short, Integer, Long, Decimal, Single, and Double data types in its overloads. Remember it returns the same type of data that you send it. It doesn’t do conversions between numeric types like previous versions of VB and BASIC when you have Option Strict On (which you should always have on). You’ll need to handle the conversion yourself.
Also, don’t forget that you have to prefix it with Math or use “Imports System.Math” in your module or project namespace. Here’s an example of this function:
Dim NewValue As Integer = Math.Abs(OldValue)
BigMul
If you’re working with big integers this function can be quite helpful in helping you avoid overflow exceptions. Remember the product of multiplying two Int32 values is an Int32 value. If your product exceeds the upper or lower Int32 range you’ll get an exception. To avoid this situation, you can use BigMul to multiply two Int32 values and return a Int64 value. Here’s a simple example:
Dim ABigNumber As Integer = 40000000 Dim AnotherBigNumber As Integer = 40000000 Dim ABigProduct As Int64 = Math.BigMul(ABigNumber, AnotherBigNumber)
DivRem
First BigMul and now DivRem, did somebody at Microsoft not get the memo about using meaningful function names? Anyway, DivRem calculates and returns the quotient of two integers, either 32 or 64 bit, plus it also returns the remainder in an output parameter. This function is handy if you want to get both the quotient and remainder in a single swoop. Here’s an example:
Dim TestIt As Integer = 578 Dim TestToo As Integer = 75 Dim TestValue As Integer Dim TestRemainder As Integer TestValue = Math.DivRem(TestIt, TestToo, TestRemainder) Debug.Print(String.Concat(TestValue, " | ", TestRemainder)) Output Value: 7 | 53
Remember to make sure that you don’t accidentally divide by zero here.
IEEERemainder
This function is sort of like DivRem except that it’s for doubles and that it returns the remainder, not the quotient (which gets dropped). Kind of an inconsistant design if you ask me. Here’s an example of this function:
Dim TestAgain As Double = 194.89482 Dim RemainderTest As Double = Math.IEEERemainder(TestAgain, Math.PI) Output Value: 0.116075477432837
Note the use of the Pi constant value in this example.
Sign
Sign is a simple, straightforward function. It returns -1 if the target number is negative, 0 if the number is zero, and 1 if the number is positive. There are overloads that will work with any of the signed number types. Here’s an example:
Select Case Math.Sign(TestAgain)
Case 1
'positive number action
Case 0
'zero action
Case -1
'negative number action
End Select
Ceiling and Floor
These functions are useful with decimal and double values where you want to obtain the nearest whole number that’s either greater than (ceiling) or less than (floor) of the given number. This could be useful in a custom rounding routine. Here are some examples and the result of the operation
Dim MyValue as Double MyValue = Math.Ceiling(194.89482) Output Value: 195 MyValue = Math.Floor(194.89482) Output Value: 194 MyValue = Math.Ceiling(-194.89482) Output Value: -194 MyValue = Math.Floor(-194.89482) Output Value: -195
Truncate
Truncate is like the old VB6/MSBASIC Fix function (this function is still in the Microsoft.VisualBasic Namespace). It simply drops the decimal portion of the target decimal or double number. Here’s the example
Dim IntValue As Integer = CInt(Math.Truncate(TestAgain))
Notice that this function also returns a double or decimal rather than an integer and this requires conversion unless you’re unwisely not using Option Strict On.
Max and Min
These functions respectively return the larger or lesser of the two numbers passed in. These functions could be quite useful for sorting routines or for random selection routines.
LowestPrice = Math.Min(NewProduct.Price, OldProduct.Price)
Pow
Pow simply raises an number to a specified power, just like the ^ operator does. I’d just use the operator myself.
Debug.Print(String.Concat(7 ^ 8)) Debug.Print(String.Concat(Math.Pow(7, 8))) Output Value for both: 5764801
Round
I covered Round in depth in this earlier article: What You Should Know About Rounding in VB.NET
I hope this article has given you a good overview of the Math class functions. While there is some redundancy there are few hidden gems as well. As always, let me know what you think by leaving a comment.
Entry Filed under: VB.NET Tutorials
Rate This Article:










1 Comment Add your own
1. links for 2007-09-21 &laq&hellip | September 21st, 2007 at 10:20 am
[...] Welcome to Math Class (.Net) (tags: dotnet) [...]
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed