Batch Script Arithmetic Operators
Arithmetic Operators
The batch script language supports arithmetic operators to perform sums, differences, multiplications, divisions and modulus.
The following table lists the available arithmetic operators.
Operator | Description | Example |
---|---|---|
+ | Addition of two operands | 1 + 2 will give 3 |
− | Subtracts second operand from the first | 2 − 1 will give 1 |
* | Multiplication of both operands | 2 * 2 will give 4 |
/ | Division of the numerator by the denominator | 3 / 2 will give 1.5 |
% | Modulus operator and remainder of after an integer/float division | 3 % 2 will give 1 |
Example
The following code snippet shows how the various operators can be used.
Example of Arithmetic Operators
@echo off
set /A a=5
set /A b=10
set /A c= %a%+%b%
echo %c%
set /A c= %a%-%b%
echo %c%
set /A c= %b%*%a%
echo %c%
set /A c=%b%/%a%
echo %c%
set /A c=%b% %% %a%
echo %c%
15
-5
50
2
0
Precedence of Arithmetic operators
The precedence of arithmetic operators is in the following order:
/ * % + -
note
The expression enclosed inside ( )
gets the highest priority in the precedence.
Let's clarify this with the following example:
PrecedenceExample.bat
@echo off
set /A s = (20 - 5) * 2 + 8 / 2
echo s = %s%
s = 34
Explanation:
(20 - 5)
gets the highest priority and calculated first giving 15.- Then division operator
/
gets next priority thus8 / 2
is evaluated giving4
. - After this multiplication operator
*
gets next priority thus15 * 2
yields30
. - Finally, addition operator
+
performs addition operation30 + 4
giving final result34
.