Today we will learn the different arithmetic operators of VBScripts. You perform calculations in VBScript in much the same way as you write out calculations longhand. The only difference is that you usually assign the result to a variable.
To add numbers, use the + operator, as shown in these two examples:
Result = 1 + 5
Result = ValueA + ValueB
To subtract numbers, use the - operator, as these two examples show:
Result = 5 - 1
Result = ValueB - ValueA
To multiply numbers, use the * operator; here are two examples of how to do that:
Result = 2 * 4
Result = ValueA * ValueB
To divide numbers, use the / or operator, as shown in the following examples:
Result = 2 / 4
Result = ValueA / ValueB
In division, you often have a remainder. Since you might want to perform calculations based on the remainder, you need a way to determine it. In VBScript, you do this by using the Mod function. For the following expression, the value of the result is set to 1:
Result = 7 Mod 2
To multiply by an exponent, use the ^ operator. This example is the same as 3 * 3 * 3 * 3:
Result = 3 ^ 4
You can also use this example, which is the same as ValueC * ValueC:
Result = ValueC ^ 2
You can negate a value by using the - operator, as shown in these two examples:
Result = -2 * 3
Result = -ValueA * ValueB
When you mix operators, VBScript performs calculations using the same precedence order your math teacher taught you. For example, multiplication and division in equations are carried out before subtraction and addition, as shown in these examples:
3 + 2 * 6 = 15
2 / 2 + 3 = 4
The complete precedence order of operators is shown in Table 30.1. According to the table, exponents have the highest precedence order and are always calculated first.
The precedence order of arithmetic operations:
Order Operation
1 Exponents (^)
2 Negation (-)
3 Multiplication (*) and Division (/)
4 Remainders (Mod)
5 Addition (+) and Subtraction (-)