How to: Calculate Numeric Values - Visual Basic (original) (raw)

You can calculate numeric values through the use of numeric expressions. A numeric expression is an expression that contains literals, constants, and variables representing numeric values, and operators that act on those values.

Calculating Numeric Values

To calculate a numeric value

To store a numeric value

Dim i As Integer = 2  
Dim j As Integer  
j = 4 * (67 + i)  

In the preceding example, the value of the expression on the right side of the equal operator (=) is assigned to the variable j on the left side of the operator, so j evaluates to 276.
For more information, see Statements.

Multiple Operators

If the numeric expression contains more than one operator, the order in which they are evaluated is determined by the rules of operator precedence. To override the rules of operator precedence, you enclose expressions in parentheses, as in the above example; the enclosed expressions are evaluated first.

To override normal operator precedence

Dim i As Integer = 2  
Dim j, k As Integer  
j = 4 * (67 + i)  
k = 4 * 67 + i  

In the preceding example, the calculation for j performs the addition operator (+) first because the parentheses around (67 + i) override normal precedence, and the value assigned to j is 276 (4 times 69). The calculation for k performs the operators in their normal precedence (* before +), and the value assigned to k is 270 (268 plus 2).
For more information, see Operator Precedence in Visual Basic.

See also