Microsoft® Windows® 2000 Scripting Guide
Most of the calculations you carry out as a system administrator are likely to be simple ones, such as dividing bytes by 1,024 to convert the value to kilobytes. On occasion, however, you might need to carry out a calculation that involves more than one operator (for example, a calculation that adds two numbers and then divides that value). Because of that, it is important to understand arithmetic precedence.
VBScript does not treat the arithmetic operators (addition, subtraction, multiplication, and division) equally. Instead, when given an equation, VBScript always performs the math operations in this order:
Why does that matter to you? Consider the following script, which adds two numbers, multiplies them by a third, subtracts a fourth, and then divides by a fifth:
Wscript.Echo 1 + 2 * 3 - 4 / 5
When this script runs, the value 6.2 is echoed to the screen. Here is how that value is derived.
Because division takes precedence over all the other operations, the first thing VBScript does is divide 4 by 5, yielding .8. To VBScript, the equation now looks like this:
1 + 2 * 3 - .8
Next it multiplies 2 and 3, yielding 6. Now the equation looks like this:
1 + 6 - .8
Because addition is next in the order of precedence, it adds 1 and 6, yielding 7, and resulting in this equation:
7 - .8
Finally it subtracts .8 from 7, giving the final answer 6.2.
Of course, this might not be the answer, or the equation, you expected. Instead, you might have preferred that VBScript:
Add 1 + 2.
Multiply that value by 3.
Divide the total by 5.
For this to happen, you need to use parentheses to indicate the preferred order of precedence. Parentheses always take precedence, regardless of the arithmetic operator being used. Because of this, your equation should be rewritten to ensure that the steps are carried out in the proper order. (When multiple parentheses are used, the equation within the innermost parentheses is evaluated first and the equation in the outermost parentheses evaluated last.)
Wscript.Echo (((1 + 2) * 3) - 4) / 5