Batchography: Arithmetic operations in Batch files

Did you know that you can do basic arithmetic operations in a Batch file script?

The syntax is simple:

set /A result=EXPR

For example, to add 10 and 20:

@echo off
set /p result=10+20
echo result=%result%

From the “SET /?” output, these are the supported arithmetic operations:

The /A switch specifies that the string to the right of the equal sign
is a numerical expression that is evaluated.  The expression evaluator
is pretty simple and supports the following operations, in decreasing
order of precedence:

    ()                  - grouping
    ! ~ -               - unary operators
    * / %               - arithmetic operators
    + -                 - arithmetic operators
    << >>               - logical shift
    &                   - bitwise and
    ^                   - bitwise exclusive or
    |                   - bitwise or
    = *= /= %= += -=    - assignment
      &= ^= |= <<= >>=
    ,                   - expression separator

Now, let’s make a simple interactive calculator:

@echo off
:main
  setlocal
  set /p num1=Enter first number:
  set /p op=Enter operator:
  set /p num2=Enter second number:

  set /a result=%num1% %op% %num2%

  echo Result is %result%

  endlocal

  goto :eof

When we enter: 4, * then 5, we get the following output:

Enter first number:4
Enter operator:*
Enter second number:5
Result is 20

The Batchography book covers this topic in details and more. Check it out!

You might also like:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.