Professional Documents
Culture Documents
Visual Studio .NET provides an easy way of performing mathematical functions, such as addi-
tion, subtraction, multiplication, division, exponentiation, integer division, and finding a remain-
der. For all other tasks, you can utilize the System.Math class.
Adds two numbers or returns the positive value of a numeric expression. Can also be used to concate-
nate two string expressions.
Example
The following example uses the + operator to add numbers. If the operands are both numeric,
Visual Basic computes the arithmetic result. The arithmetic result represents the sum of the two
operands.
VB
You can also use the + operator to concatenate strings. If the operands are both strings, Visual
Basic concatenates them. The concatenation result represents a single string consisting of the
contents of the two operands one after the other.
If the operands are of mixed types, the result depends on the setting of the Option Strict State-
ment. The following example illustrates the result when Option Strict is On.
VB
Option Strict On
VB
Dim var1 As String = "34"
Dim var2 As Integer = 6
Dim concatenatedNumber As Integer = var1 + var2
VB
' The preceding statement generates a COMPILER ERROR.
The following example illustrates the result when Option Strict is Off.
VB
Option Strict Off
VB
Dim var1 As String = "34"
Dim var2 As Integer = 6
Dim concatenatedNumber As Integer = var1 + var2
VB
' The preceding statement returns 40 after the string in var1 is
' converted to a numeric value. This might be an unexpected result.
To eliminate ambiguity, you should use the & operator instead of + for concatenation.
Example
The following example uses the – operator to calculate and return the difference between two
numbers, and then to negate a number.
VB
Dim binaryResult As Double = 459.35 - 334.9
Dim unaryResult As Double = -334.9
Following the execution of these statements, binaryResult contains 124.45 and unaryResult
contains –334.90.
Example
This example uses the / operator to perform floating-point division. The result is the quotient of
the two operands.
VB
Example
The following example uses the \ operator to perform integer division. The result is an integer
that represents the integer quotient of the two operands, with the remainder discarded.
VB
Example
The following example uses the Mod operator to divide two numbers and return only the remain-
der. If either number is a floating-point number, the result is a floating-point number that repre-
sents the remainder.
VB
Console.WriteLine(10 Mod 5)
' Output: 0
Console.WriteLine(10 Mod 3)
' Output: 1
Console.WriteLine(-10 Mod 3)
' Output: -1
Console.WriteLine(12 Mod 4.3)
' Output: 3.4
Console.WriteLine(12.6 Mod 5)
' Output: 2.6
Console.WriteLine(47.9 Mod 9.35)
' Output: 1.15
Parts
number
Required. Any numeric expression.
exponent
Required. Any numeric expression.
Result
The result is number raised to the power of exponent, always as a Double value.
Supported Types
Double. Operands of any different type are converted to Double.
Remarks
Visual Basic always performs exponentiation in the Double Data Type.
The value of exponent can be fractional, negative, or both.
When more than one exponentiation is performed in a single expression, the ^ operator is evalu-
ated as it is encountered from left to right.
Note
The ^ operator can be overloaded, which means that a class or structure can redefine its behav-
ior when an operand has the type of that class or structure. If your code uses this operator on
such a class or structure, be sure you understand its redefined behavior. For more information,
see Operator Procedures.
Example
The following example uses the ^ operator to raise a number to the power of an exponent. The
result is the first operand raised to the power of the second.
VB
Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the ^= operator can be a simple scalar variable, a property, or an
element of an array. The variable or property cannot be ReadOnly.
The ^= operator first raises the value of the variable or property (on the left-hand side of the op-
erator) to the power of the value of the expression (on the right-hand side of the operator). The
operator then assigns the result of that operation back to the variable or property.
Visual Basic always performs exponentiation in the Double Data Type. Operands of any differ-
ent type are converted to Double, and the result is always Double.
The value of expression can be fractional, negative, or both.
Overloading
The ^ Operator can be overloaded, which means that a class or structure can redefine its behav-
ior when an operand has the type of that class or structure. Overloading the ^ operator affects the
behavior of the ^= operator. If your code uses ^= on a class or structure that overloads ^, be sure
you understand its redefined behavior.
Example
The following example uses the ^= operator to raise the value of one Integer variable to the
power of a second variable and assign the result to the first variable.
VB
However, for other operations, you can use the methods available in the System.Math class.
Atan2 Returns the angle whose tangent is the quotient of two specified numbers.
Returns the smallest integral value that's greater than or equal to the specified
Ceiling
Decimal or Double.
Returns the quotient of two 32-bit or 64-bit signed integers, and also returns the
DivRem
remainder in an output parameter.
Exp Returns e (the base of natural logarithms) raised to the specified power.
Returns the largest integer that's less than or equal to the specified Decimal or
Floor
Double number.
Returns the remainder that results from the division of a specified number by
IEEERemainder
another specified number.
Log Returns the natural (base e) logarithm of a specified number or the logarithm of
.NET Framework
Description
method
To use these functions without qualification, import the System.Math namespace into your
project by adding the following code to the top of your source file:
Imports System.Math
Example
This example uses the Abs method of the Math class to compute the absolute value of a number.
' Returns 50.3.
Dim MyNumber1 As Double = Math.Abs(50.3)
' Returns 50.3.
Dim MyNumber2 As Double = Math.Abs(-50.3)
Example
This example uses the Atan method of the Math class to calculate the value of pi.
Public Function GetPi() As Double
' Calculate the value of pi.
Return 4.0 * Math.Atan(1.0)
End Function
Example
This example uses the Cos method of the Math class to return the cosine of an angle.
Public Function Sec(ByVal angle As Double) As Double
' Calculate the secant of angle, in radians.
Return 1.0 / Math.Cos(angle)
End Function
Example
This example uses the Exp method of the Math class to return e raised to a power.
Public Function Sinh(ByVal angle As Double) As Double
' Calculate hyperbolic sine of an angle, in radians.
Return (Math.Exp(angle) - Math.Exp(-angle)) / 2.0
End Function
Example
This example uses the Log method of the Math class to return the natural logarithm of a number.
Public Function Asinh(ByVal value As Double) As Double
' Calculate inverse hyperbolic sine, in radians.
Return Math.Log(value + Math.Sqrt(value * value + 1.0))
End Function
Example
This example uses the Round method of the Math class to round a number to the nearest integer.
' Returns 3.
Dim MyVar2 As Double = Math.Round(2.8)
Example
This example uses the Sign method of the Math class to determine the sign of a number.
' Returns 1.
Dim MySign1 As Integer = Math.Sign(12)
' Returns -1.
Dim MySign2 As Integer = Math.Sign(-2.4)
' Returns 0.
Dim MySign3 As Integer = Math.Sign(0)
Example
This example uses the Sin method of the Math class to return the sine of an angle.
Public Function Csc(ByVal angle As Double) As Double
' Calculate cosecant of an angle, in radians.
Return 1.0 / Math.Sin(angle)
End Function
Example
This example uses the Sqrt method of the Math class to calculate the square root of a number.
' Returns 2.
Dim MySqr1 As Double = Math.Sqrt(4)
' Returns 4.79583152331272.
Dim MySqr2 As Double = Math.Sqrt(23)
' Returns 0.
Dim MySqr3 As Double = Math.Sqrt(0)
' Returns NaN (not a number).
Dim MySqr4 As Double = Math.Sqrt(-4)
Example
This example uses the Tan method of the Math class to return the tangent of an angle.
Public Function Ctan(ByVal angle As Double) As Double
' Calculate cotangent of an angle, in radians.
Return 1.0 / Math.Tan(angle)
End Function
Requirements
Class: Math
Namespace: System
Example
Private Sub PerformMathFunctions()
i = Math.Pow(2, 3)
MessageBox.Show(i)
i = Math.Sqrt(16)
MessageBox.Show(i)
i = Math.Round(5.34444)
MessageBox.Show(i)
How it works
First, I define an integer type variable i. Then, I assign the value of 2 taken to the third power and
display the result in the message box (the value displayed is 8). The value of i is then set to the
value of the square root of 16, and its value is displayed in the message box (the value displayed
is 4). And finally, I set the value of the variable i to the result of rounding the number 5.34444
and show the result in the message box (the value displayed is 5).
VB.NET program that computes absolute values
Module Module1
Sub Main()
' Absolute values of integers.
Dim value1 As Integer = -1000
Dim value2 As Integer = 20
Dim abs1 As Integer = Math.Abs(value1)
Dim abs2 As Integer = Math.Abs(value2)
Console.WriteLine(value1)
Console.WriteLine(abs1)
Console.WriteLine(value2)
Console.WriteLine(abs2)
Console.WriteLine(value3)
Console.WriteLine(abs3)
Console.WriteLine(value4)
Console.WriteLine(abs4)
End Sub
End Module
Output
-1000
1000
20
20
-100.123
100.123
20.2
20.2
Precedence Rules
When expressions contain operators from more than one category, they are evaluated according
to the following rules:
· The arithmetic and concatenation operators have the order of precedence described in the
following section, and all have greater precedence than the comparison, logical, and bit-
wise operators.
· All comparison operators have equal precedence, and all have greater precedence than
the logical and bitwise operators, but lower precedence than the arithmetic and concate-
nation operators.
· The logical and bitwise operators have the order of precedence described in the following
section, and all have lower precedence than the arithmetic, concatenation, and compari-
son operators.
· Operators with equal precedence are evaluated left to right in the order in which they ap-
pear in the expression.
Precedence Order
Operators are evaluated in the following order of precedence:
Await Operator
Await
Arithmetic and Concatenation Operators
Exponentiation (^)
Unary identity and negation (+, –)
Multiplication and floating-point division (*, /)
Integer division (\)
Modulus arithmetic (Mod)
Addition and subtraction (+, –)
String concatenation (&)
Arithmetic bit shift (<<, >>)
Comparison Operators
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Logical and Bitwise Operators
Negation (Not)
Conjunction (And, AndAlso)
Inclusive disjunction (Or, OrElse)
Exclusive disjunction (Xor)
Comments
The = operator is only the equality comparison operator, not the assignment operator.
The string concatenation operator (&) is not an arithmetic operator, but in precedence it is
grouped with the arithmetic operators.
The Is and IsNot operators are object reference comparison operators. They do not compare the
values of two objects; they check only to determine whether two object variables refer to the
same object instance.
Associativity
When operators of equal precedence appear together in an expression, for example multiplication
and division, the compiler evaluates each operation as it encounters it from left to right. The fol-
lowing example illustrates this.
Dim n1 As Integer = 96 / 8 / 4
Dim n2 As Integer = (96 / 8) / 4
Dim n3 As Integer = 96 / (8 / 4)
The first expression evaluates the division 96 / 8 (which results in 12) and then the division 12 /
4, which results in three. Because the compiler evaluates the operations for n1 from left to right,
the evaluation is the same when that order is explicitly indicated for n2. Both n1 and n2 have a
result of three. By contrast, n3 has a result of 48, because the parentheses force the compiler to
evaluate 8 / 4 first.
Because of this behavior, operators are said to be left associative in Visual Basic.
3 The flowchart inputs an integer. The predefined function DIV gives the integer result of the di-
vision, e.g. Y 10 DIV 3 gives the value Y = 3. The predefined function MOD gives the
value of the remainder, e.g. Y 10 MOD 3 gives the value Y = 1.